I have a function that is to be called by a thread initiated with a start and end parameter. The function works fine when run on single, main thread. However, when I try multi threading on it, the code breaks.
The function is as below:
static void processThread(long startLimit, long endLimit)
{
long rangeLimit = startLimit;
while (startLimit < endLimit) {
rangeLimit = rangeLimit + 100;
startLimit++;
Console.WriteLine("Processed for " + startLimit + ", " + rangeLimit);
startLimit = rangeLimit;
}
}
I am calling it from main as::
int threadCount = 4;
long[] startPoints = new long[threadCount];
long[] endPoints = new long[threadCount];
if ((endLimit / 100) % threadCount == 0)
{
for (int i = 0; i < threadCount; i++)
{
endPoints[i] = endLimit * (i + 1) / threadCount;
}
startPoints[0] = 0;
for (int i = 1; i < threadCount; i++)
{
startPoints[i] = endPoints[i - 1];
}
}
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(() => processThread(startPoints[i], endPoints[i]));
threads[i].Start();
Console.WriteLine("Started for " + startPoints[i] + ", " + endPoints[i]);
}
The expected result is something like
Processed for 1, 100
Processed for 101, 200
Processed for 201, 300
Processed for 301, 400
Processed for 401, 500
Processed for 501, 600
Processed for 601, 700
Processed for 701, 800
.....
And so on... But what I am getting is:
Started for 0, 2500
Started for 2500, 5000
Processed for 5001, 5100
Processed for 5101, 5200
Processed for 5201, 5300
Processed for 5301, 5400
Processed for 5401, 5500
Processed for 5501, 5600
Processed for 5601, 5700
Processed for 5001, 5100
Started for 5000, 7500
Processed for 5001, 5100
Processed for 5101, 5200
Processed for 5201, 5300
Processed for 5301, 5400
Processed for 5401, 5500
Processed for 5501, 5600
Processed for 5601, 5700
Processed for 5701, 5800
Processed for 5801, 5900
Processed for 5901, 6000
Processed for 6001, 6100
Processed for 6101, 6200
Started for 7500, 10000
Processed for 6201, 6300
Processed for 6301, 6400
Processed for 6401, 6500
Processed for 6501, 6600
Processed for 5701, 5800
Which has many repeated values and has none from the range 0-2500. I also tried with Task.Factory, and got the same result.
Any help on this would be greatly appreciated.