So I have a simple program that is supposed to add some elements to a ConcurrentQueue, then spawn 5 threads to output the elements in the Queue. However, the output is unpredictable and I assume there is some race condition that is occurring. But I don't know how or why it is happening.
class Program
{
static ConcurrentQueue<int> queue = new ConcurrentQueue<int>();
static int threadsMax = 5; // Max amount of threads to spawn
static Thread[] threads = new Thread[threadsMax];
static void Main(string[] args)
{
queue.Enqueue(100);
queue.Enqueue(200);
queue.Enqueue(300);
queue.Enqueue(400);
queue.Enqueue(500);
int test = 0;
for (int i = 0; i < threadsMax; i++)
{
queue.TryDequeue(out test);
threads[i] = new Thread(delegate () { WorkerThread(test); });
threads[i].Start();
}
Console.ReadKey();
}
static void WorkerThread(int test)
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Test: " + test);
}
}
I figured it might show the results out of order depending on how the OS schedules the threads, but instead it shows repeated elements in the queue. I tried using a lock to no avail, but that makes sense because there is only 1 thread accessing the queue, at least that I know of. Any help understanding this would be greatly appreciated!
Typical output:
4 Test: 400
5 Test: 400
3 Test: 400
6 Test: 500
7 Test: 500