0

I am trying to split the work of working over a list of integers, by multithreading. The following loop is not multithreaded, however if i run my code it calls an out of index.

//dummy values
int t = 2;
int[] list = new int[t] {1,2}
int[] sd = new int[t+1] {1,2,3}



for (int i = 0; i < t; i++)
        {
            list[i] = new Thread(() => func(sd[i], sd[i+1]));
            list[i].Start();
        }

When i check the out of index error i see that i has gone up to 2, which shouldnt happen. When i place a breakpoint and go through step by step, my program terminates just fine.

Even when changing the i to an unused character, or when splitting the new Thread and Start into seperate forloops, the same happens.

  • 1
    You are starting a thread that has a reference to `i`, the loop variable. It doesn't have the value of `i`, because you didn't give it that. You gave it a reference to `i`. The loop ends when `i` is equal to `t`. `t` is equal to 2. After the loop completes, the thread procs have references to `i`, which is equal to 2. You need to use a `foreach` loop, which fixes this problem Or else store the value of `i` in a local variable within the loop block and use that in the thread block. – 15ee8f99-57ff-4f92-890c-b56153 Nov 21 '17 at 14:03
  • If you don't understand my explanation, **use the debugger** to step through every tiny piece of the loop until you understand that the thread procs execute after the loop finishes, and that at that time, `i == 2` because that is what you told it to do in the code. In the debugger you can watch and see that the loop increments `i` to 2 and then stops. If the loop stops when `i` is *not less* than `t`, obviously at some point, `i` must become equal to or greater than `t`. – 15ee8f99-57ff-4f92-890c-b56153 Nov 21 '17 at 14:07
  • Yesterday a guy argued with me about this for two hours before he finally **used the debugger** and understood what was happening. [Here is his explanation when he finally figured it out](https://stackoverflow.com/questions/47398377/adding-method-to-delegate-changes-iteration-in-for-loop-c-sharp-issue/47398548?noredirect=1#comment81754776_47398548). Maybe that will help. – 15ee8f99-57ff-4f92-890c-b56153 Nov 21 '17 at 14:07

0 Answers0