Do I need to use locking in the following C # code?

In the following code, I use two threads to share a resource in this example: queue , so I need to use lock , and en-queueing or dequeuing , if so, why, because the program works fine.

 class Program { static Queue<string> sQ = new Queue<string>(); static void Main(string[] args) { Thread prodThread = new Thread(ProduceData); Thread consumeThread = new Thread(ConsumeData); prodThread.Start(); consumeThread.Start(); Console.ReadLine(); } private static void ProduceData() { for (int i = 0; i < 100; i++) { sQ.Enqueue(i.ToString()); } } private static void ConsumeData() { while (true) { if (sQ.Count > 0) { string s = sQ.Dequeue(); Console.WriteLine("DEQUEUE::::" + s); } } } } 
+4
source share
1 answer

Yes you do, System.Collections.Generic.Queue<T> not thread safe to write and read at the same time. You need to either lock a single object before appearing or decompressing, or if you are using .NET 4 / 4.5, use the System.Collections.Concurrent.ConcurrentQueue<T> class and use the TryDequeue method.

The reason your current implementation has not called you so far is caused by calling Thread.Sleep(500) (not what you should use in production code), which means that prodThread not being written to the queue while consumeThread is consumeThread read from it, since the read operation takes less than 500 ms. If you remove the Thread.Sleep coefficients, this will throw an exception at some point.

+8
source

All Articles