This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace FirePrime
{
class P
The value the thread receives is the one startNum
holds when the thread runs. To solve it copy the value into a local variable:
for (int i = 0; i < nrThreads; i++)
{
var localStartNum = startNum; // save value in local variable
// and use in the thread start
var localIndex = i;
var _thread = new System.Threading.Thread(() =>
MarkPrimes(localStartNum,
Math.Min(localStartNum + interval, nrNums),
localIndex));
startNum = startNum + interval;
_thread.IsBackground = true;
_thread.Start();
}
Another bug in the code is waiting for all threads:
static bool AllThreadsFinished()
{
bool allThreadsFinished = true; // Initialize to true instead of false
// Otherwise, all ANDs will result false
foreach (var threadFinished in ThreadsFinished)
{
allThreadsFinished = threadFinished;
}
return allThreadsFinished;
}
One tip which can help a little in synchronizing the threads: You can save all the threads in a list and join them from main thread.
var threads = new List<Thread>();
for (int i = 0; i < nrThreads; i++)
{
var localStartNum = startNum; // save value in local variable
// and use in the thread start
var _thread = new System.Threading.Thread(() =>
MarkPrimes(localStartNum,
Math.Min(localStartNum + interval, nrNums), i));
startNum = startNum + interval;
_thread.IsBackground = true;
_thread.Start();
threads.Add(_thread);
}
foreach(var thread in threads)
{
thread.Join();
}