Thread parameters are changing

When starting multiple threads, the id parameter that I am processing is sometimes erroneous. Here is my launch:

 for (int i = 0; i < _threadCount; i++) { Thread thread = new Thread(() => WorkerThread(i)); thread.Start(); _threads.Add(thread); } 

And my stream function:

 private void WorkerThread(int id) { Console.WriteLine("[{0}] Thread started {1}", DateTime.Now.ToLongTimeString(), id); } 

The output of this code is:

 [19:10:54] Thread start 3 [19:10:54] Thread start 9 [19:10:54] Thread start 4 [19:10:54] Thread start 12 [19:10:54] Thread start 11 [19:10:54] Thread start 3 [19:10:54] Thread start 12 [19:10:54] Thread start 6 [19:10:54] Thread start 9 [19:10:54] Thread start 6 [19:10:54] Thread start 13 [19:10:54] Thread start 2 [19:10:54] Thread start 15 [19:10:54] Thread start 9 [19:10:54] Thread start 15 

Where, in my opinion, this code should create each thread with a unique id instead of duplicates, as shown above.

Compiler Information:

Platform Target: x64

Target Structure: .NET Framework 4.5

+7
multithreading c #
source share
2 answers

You should be careful when accidentally changing captured variables, such as i after starting the stream, since i common . The variable i refers to the same memory cell throughout the cycle. The solution is to use a temporary variable as follows:

 for (int i = 0; i < _threadCount; i++) { var i1 = i; Thread thread = new Thread(() => WorkerThread(i1)); thread.Start(); _threads.Add(thread); } 

More on Closures here: The beauty of closures (Jon Skeet) and Lambda expressions and captured variables from (Joseph Albahari).

+9
source share

The problem is that the variable i refers to the same memory location after the cycle time. Therefore, each thread calls a variable whose value may change as it starts. The solution is a temporary user variable int temp = i . as S.Ackbari said.

0
source share

All Articles