Posts

Showing posts from February, 2009
A quick solution to producer consumer problem. I am sure this can be improved..(and might even have bugs).. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Algorithms { class ProducerConsumer { private static Queue<int> buffer = new Queue<int>(); static AutoResetEvent producerEvent = new AutoResetEvent(false); static AutoResetEvent consumerEvent = new AutoResetEvent(false); public static void Producer() { while (true) { lock(buffer) { if (buffer.Count == 0) { buffer.Enqueue(1); Console.WriteLine( Thread.CurrentThread.Name + "has produced"); consumerEvent.Set(); } } } } public static void Consumer() { while(true) { lock(buffer) { if (buffer.Count == 1) { buffer.Dequeue(); Console.WriteLine( Thread.CurrentThread.Name + "has consumed"); } }