Program.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace RingBuffer
  8. {
  9. internal class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. var queue = new LockFreeRingBuffer<int>(10000);
  14. int hasData = 1000;
  15. int shouldContinue = 1000;
  16. Task.Factory.StartNew(async () =>
  17. {
  18. // 生产者线程
  19. while (hasData>0)
  20. {
  21. if (!queue.TryEnqueue(hasData))
  22. {
  23. Thread.Sleep(1); // 队列满时短暂等待
  24. }
  25. Console.WriteLine("生产者添加了{0}", hasData);
  26. // 模拟生产延迟
  27. await Task.Delay(10);
  28. hasData--;
  29. }
  30. });
  31. Task.Factory.StartNew(async () =>
  32. {
  33. // 消费者线程
  34. while (shouldContinue > 0)
  35. {
  36. if (queue.TryDequeue(out var item))
  37. {
  38. Console.WriteLine("消费者处理了{0}", item);
  39. // 模拟生产延迟
  40. await Task.Delay(10);
  41. }
  42. }
  43. });
  44. Console.ReadLine();
  45. }
  46. }
  47. }