Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- namespace ProducerConsumer
- {
- class MyParams
- {
- public bool isStop;
- }
- class Program
- {
- static int capacity = 3;
- static int storage = 0;
- static object locker = new object();
- static AutoResetEvent consumerHandle = new AutoResetEvent(false);
- static AutoResetEvent producerHandle = new AutoResetEvent(false);
- public static void Produce(object param)
- {
- var myparam = (MyParams)param;
- while (!myparam.isStop)
- {
- if (storage >= capacity)
- {
- Console.WriteLine("Producer: storage full");
- consumerHandle.WaitOne();
- }
- lock (locker)
- {
- storage += 1;
- Console.WriteLine($"Producer: product produced, left: {storage}");
- producerHandle.Set();
- }
- Thread.Sleep((new Random()).Next(2, 2) * 100);
- }
- }
- public static void Consume(object param)
- {
- var myparam = (MyParams)param;
- while (!myparam.isStop)
- {
- if (storage <= 0)
- {
- Console.WriteLine("Consumer: storage empty");
- producerHandle.WaitOne();
- }
- lock (locker)
- {
- storage -= 1;
- Console.WriteLine($"Consumer: product taken, left: {storage}");
- consumerHandle.Set();
- }
- Thread.Sleep((new Random()).Next(9, 10) * 100);
- }
- }
- static void Main(string[] args)
- {
- MyParams param = new MyParams { isStop = false };
- Thread thr1 = new Thread(Produce);
- Thread thr2 = new Thread(Consume);
- thr1.Start(param);
- thr2.Start(param);
- Console.ReadLine();
- param.isStop = true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement