List of workflows generated by for loop outperforms for-loop iteration

I am relatively green for the right thread, I have this, it has been changed for simplicity, but in essence it is one and the same:

//Global: N=2 bool[] mySwitches; //In my main: mySwitches = new bool[N]; for (int i = 0; i < N; i++) { ThreadList.Add(new Thread(() => Worker(i))); ThreadList[i].Start(); } //Outside of main: Private Void Worker(int num) { while(true) { if (mySwitches[num]) //error happes here because num is equal to N, how? { //do something } } } 

As shown above, somehow the worker thread gets the value num = N, I expect it to reach only N-1. I know that I will get an increment after creating the Worker, am I somehow passing by reference instead of value?

I tried to fix the problem by setting a test before my while loop returns if num = N, but even with this position I get the same error. This makes me think that the number is somehow increasing after the start of the stream.

I fixed this problem by putting Sleep (20) immediately after ThreadList [i] .Start (), but I don’t really like to use “Sleep”, and it’s clear that I don’t know how this streaming script really works.

Can anyone shed some light on this?

+4
source share
1 answer

i is fixed by reference. Change your code as

 for (int i = 0; i < N; i++) { var thInx = i; ThreadList.Add(new Thread(() => Worker(thInx))); ThreadList[thInx].Start(); } 

For more information: http://csharpindepth.com/articles/chapter5/closures.aspx

+5
source

All Articles