If we use concurrent queue, we can just throw away all the complicated lock mechanism or concurrency and focus on the logic itself. Not sure if c# concurrent queue implemented it with lock free mechanism but producer-consumer code can be written in less than 100 lines.
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SimpleProducerConsumer { class Producer { private ConcurrentQueue<int> q; public Producer(ConcurrentQueue<int> q) { this.q = q; } public void Run() { while (true) { int w; Console.Write("Gimme a work: "); w = Convert.ToInt32(Console.ReadLine()); this.q.Enqueue(w); Console.WriteLine(); } } } class Consumer { private ConcurrentQueue<int> q; public Consumer(ConcurrentQueue<int> q) { this.q = q; } public void Run() { while (true) { int w = -1; if (q.TryDequeue(out w)) { Console.WriteLine("\nExtracted {0} from the queue and processed", w); } Thread.Sleep(1000); } } } class Program { static void Main(string[] args) { var q = new ConcurrentQueue<int>(); var producer = new Producer(q); var consumer = new Consumer(q); Thread tProducer = new Thread(producer.Run); Thread tConsumer = new Thread(consumer.Run); tConsumer.Start(); tProducer.Start(); } } }
No comments:
Post a Comment