Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace ProducerConsumer
  5. {
  6. class MyParams
  7. {
  8. public bool isStop;
  9. }
  10.  
  11. class Program
  12. {
  13. static int capacity = 3;
  14. static int storage = 0;
  15. static object locker = new object();
  16. static AutoResetEvent consumerHandle = new AutoResetEvent(false);
  17. static AutoResetEvent producerHandle = new AutoResetEvent(false);
  18.  
  19. public static void Produce(object param)
  20. {
  21. var myparam = (MyParams)param;
  22. while (!myparam.isStop)
  23. {
  24. if (storage >= capacity)
  25. {
  26. Console.WriteLine("Producer: storage full");
  27. consumerHandle.WaitOne();
  28. }
  29. lock (locker)
  30. {
  31. storage += 1;
  32. Console.WriteLine($"Producer: product produced, left: {storage}");
  33. producerHandle.Set();
  34.  
  35. }
  36. Thread.Sleep((new Random()).Next(2, 2) * 100);
  37. }
  38. }
  39.  
  40. public static void Consume(object param)
  41. {
  42. var myparam = (MyParams)param;
  43. while (!myparam.isStop)
  44. {
  45. if (storage <= 0)
  46. {
  47. Console.WriteLine("Consumer: storage empty");
  48. producerHandle.WaitOne();
  49. }
  50. lock (locker)
  51. {
  52. storage -= 1;
  53. Console.WriteLine($"Consumer: product taken, left: {storage}");
  54. consumerHandle.Set();
  55.  
  56. }
  57. Thread.Sleep((new Random()).Next(9, 10) * 100);
  58. }
  59. }
  60.  
  61. static void Main(string[] args)
  62. {
  63. MyParams param = new MyParams { isStop = false };
  64. Thread thr1 = new Thread(Produce);
  65. Thread thr2 = new Thread(Consume);
  66. thr1.Start(param);
  67. thr2.Start(param);
  68. Console.ReadLine();
  69. param.isStop = true;
  70. }
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement