using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace ConsoleApplication1 { public class Buffer { private Pair data; private bool empty = true; public void Read(ref Pair data) { lock(this) { // Check whether the buffer is empty. if (empty) Monitor.Wait(this); empty = true; data.key = this.data.key; data.colour = this.data.colour; data.trace(" read :"); Monitor.Pulse(this); } } public void Write(Pair data) { lock(this) { // Check whether the buffer is full. if (!empty) Monitor.Wait(this); empty = false; this.data.key = data.key; this.data.colour = data.colour; this.data.trace("wrote :"); Monitor.Pulse(this); } } public void Start() { } }// end class Buffer public class Producer { private Buffer buffer; private Random random = new Random(); public Producer(Buffer buffer) { this.buffer = buffer; } public void Production() { Pair p = new Pair(0, 0); for(int i=1; i<=10; i++) { // delay up to 500 milliseconds. Thread.Sleep(random.Next(501)); p.key = i; p.colour = i; buffer.Write(p); } } } public class Consumer { private Buffer buffer; private Random random = new Random(); public Consumer(Buffer buffer) { this.buffer = buffer; } public void Consumption() { Pair data = new Pair(0,0); string hold_up; for(int i=1; i<=10; i++) { // delay up to 500 milliseconds. Thread.Sleep(random.Next(501)); buffer.Read(ref data); } Console.WriteLine("\nplease return to terminate"); hold_up =Console.ReadLine(); } } public struct Pair { public int key ; public int colour ; public Pair(int key, int colour) { this.key = key; this.colour = colour; } public void trace(string s) { Console.Write(s +" key : " + key ); Console.WriteLine(" colour : " + colour); } } public class TheOne { public static void Main() { Buffer buff = new Buffer(); Producer prod = new Producer(buff); Consumer con = new Consumer(buff); Thread ProducerThread = new Thread(new ThreadStart( prod.Production)); Thread ConsumerThread = new Thread(new ThreadStart( con.Consumption)); ProducerThread.Start(); ConsumerThread.Start(); } } }