In the following example, it seems that the index i
of the for-loop is modified independently by each thread leading to strange values of i
(multiples, even values larger than System.Environment.ProcessorCount-1
) in DoWork_Threaded()
How are multithreaded loops properly done in C# ?
// Prepare all threads
Thread[] threads = new Thread[System.Environment.ProcessorCount];
// Start all threads
for (int i = 0; i < System.Environment.ProcessorCount; i++)
{
threads[i] = new Thread(() => DoWork_Threaded(i));
threads[i].Start();
}
// Wait for completion of all threads
for (int i = 0; i < System.Environment.ProcessorCount; i++)
{
threads[i].Join();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…