Index out of bounds when create new thread with parameters?

元气小坏坏 提交于 2019-11-29 17:07:01

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!