Jiig
Jiig

Reputation: 105

Loop for creating different threads spawns multiple of the same one

I'm using the following code to create multiple threads that will work on an array in the given ranges (min, max)

When I ran this code only the bottom half of the array was being modified, so i put the name field into Threads.advance so that I could print out the number of the thread, when i did i got the following:

Thread Stopped: 2 Range: 25 50
Thread Stopped: 2 Range: 25 50

This is confusing for two reasons:

1) The numThreads variable is 2, so the for loop should be going from 0 to 1, but the name is printing as 2.

2) All of the threads that are being spawned have the same range and name, even though the values I'm passing in change during the for loop.

Task[] tasks = new Task[numThreads];
int minRange, maxRange;
for (int i = 0; i < numThreads; i++)
{
    minRange = worldlength / numThreads * i;
    maxRange = worldlength / numThreads * (i + 1);
    tasks[i] = (Task.Factory.StartNew(() => Threads.advance(minRange, maxRange, i.ToString())));
}                    
Console.WriteLine();
Task.WaitAll(tasks);

Upvotes: 1

Views: 163

Answers (1)

Enigmativity
Enigmativity

Reputation: 117055

Try changing your loop to be like this:

// int minRange, maxRange; - declare inside loop instead!!
for (int i = 0; i < numThreads; i++)
{
    var i2 = i;
    int minRange = worldlength / numThreads * i;
    int maxRange = worldlength / numThreads * (i + 1);
    tasks[i] = (Task.Factory.StartNew(() => 
            Threads.advance(minRange, maxRange, i2.ToString())));
}   

That should give you the correct output as you need to capture the variable inside the loop before passing it inside a task.

Upvotes: 2

Related Questions