Index out of bounds when create new thread with parameters?

后端 未结 1 336
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 12:46

I\'m working on my project about Bakery Algorithm but i don\'t have any demo of that Algorithm in C# . Because of that situation i\'ve converted some java code that i found

相关标签:
1条回答
  • 2020-12-21 13:17

    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.

    0 讨论(0)
提交回复
热议问题