Synchronization of production and consumption is a classic example which can be implemented by using Threads. A Producer produces a product and a Consumer consumes the product only when the production is done. Similarly; a Producer produces the next serial only when the Consumer has consumed the previous serial. If there is no proper synchronization between the Producer and Consumer, there may be overrun of production resulting in the Consumer missing out some serials or there may be repeated consumption of the same serial by the Consumer. Presented here is a pair of Producer and Consumer which produces and consumes a ShartInt object which is nothing but a wrapper of the simple int. The Producer and Consumer signals each other about their completion status using a shared AutoResetEvent.
The object of production/ consumption, SharedInt
public class SharedInt { int i; public SharedInt(int i) { this.i = i; }
public int I { get { return i; } set { i = (int)value; } } }
The Producer class:
public class Producer { SharedInt i; AutoResetEvent evnt;
public Producer(SharedInt i, AutoResetEvent evnt) { this.i = i; this.evnt = evnt; }
public void Produce() { for (int ii = 0; ii < 10; ii++) { i.I = ++i.I; Console.WriteLine("i produced:{0}", i.I); //Signal the waiting Consumer evnt.Set(); //Go on wait until the Consumer signals evnt.WaitOne(); } } }
The Consumer class:
public class Consumer { SharedInt i; AutoResetEvent evnt; public Consumer(SharedInt i, AutoResetEvent evnt) { this.i = i; this.evnt = evnt; }
public void Consume() { for (int ii = 0; ii < 10; ii++) { //Wait until the Producer signals evnt.WaitOne(); Console.WriteLine("i consumed:{0}", i.I); //Signal the waiting Producer evnt.Set(); } } }
And finally the Simulator class:
public class ProdAndConsumRunner { public void Run() { SharedInt sharedInt = new SharedInt(0); AutoResetEvent evnt = new AutoResetEvent(false); Producer producer = new Producer(sharedInt, evnt); Consumer consumer = new Consumer(sharedInt, evnt); Thread prodThread = new Thread(new ThreadStart(producer.Produce)); Thread consumThread = new Thread(new ThreadStart(consumer.Consume)); prodThread.Start(); consumThread.Start(); prodThread.Join(); consumThread.Join(); } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|