This is the problem:
threadArray[i] = new Thread(() => simThread(i));
You're capturing i
here - the single variable which will be updated over the course of the loop, and end up with a value of threads
.
If the thread only actually executes the body of the lambda expression after the loop is completed, that value will basically be inappropriate... and even if it doesn't, you could easily have multiple threads using the same value of i
.
You basically want a separate variable for each iteration of the loop, e.g.
for (int i = 0; i < threads; i++)
{
int copy = i;
threadArray[i] = new Thread(() => simThread(copy));
Console.WriteLine("[He Thong] PID " + i.ToString() + " duoc khoi tao");
threadArray[i].Start();
}
That way each iteration of the loop captures a separate variable which has the value of i
for that iteration, but which isn't then changed.
That's the smallest change between your current code and working code - but personally I'd be looking to make larger changes to use the TPL more heavily, have separate self-contained objects instead of parallel arrays etc.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…