Use lock and Monitor to coordinate Producer and Consumer : Monitor « Thread « C# / CSharp Tutorial






using System;
using System.Threading;
public class SyncExample
{
  public static void Main()
  {
    Data dt = new Data();
    Producer p = new Producer(dt);
    Consumer c = new Consumer(dt);
    Thread pt = new Thread(new ThreadStart(p.run));
    Thread ct = new Thread(new ThreadStart(c.run));
    pt.Start();
    ct.Start();
  }
}
public class Producer
{
  private Data data;
  public Producer(Data data)
  {
    this.data = data;
  }
  public void run()
  {
    while (true)
    {
      data.produce();
      Thread.Sleep(1000);
    }
  }
}
public class Consumer
{
  private Data data;
  public Consumer(Data data)
  {
    this.data = data;
  }
  public void run()
  {
    while (true)
    {
      data.consume();
      Thread.Sleep(1000);
    }
  }
}
public class Data
{
  public int value=0;
  public bool isReady = false;
  public void produce()
  {
    lock(this)
    {
      if (isReady)
        Monitor.Wait(this);        
      value++;
      Console.WriteLine("Produced:"+value);
      isReady = true;
      Monitor.Pulse(this);
    }
  }
  public void consume()
  {
    lock(this)
    {
      if (!isReady)
        Monitor.Wait(this);
      Console.WriteLine("Consumed:"+value);
      isReady = false;
      Monitor.Pulse(this);
        
    }
  }
}








20.19.Monitor
20.19.1.Use Wait() and Pulse() to create a ticking clock
20.19.2.Use Monitors
20.19.3.Monitor: Enter and Exit
20.19.4.Monitor: try to enter
20.19.5.Coordinate two threads using Monitor
20.19.6.Use Monitor to control more than one Threads
20.19.7.Increment Monitor
20.19.8.Monitor Pool
20.19.9.Throw exception between Monitor.Enter and Montor.Exit
20.19.10.Using A Monitor
20.19.11.Use lock and Monitor to coordinate Producer and Consumer