Reputation: 1183
When starting multiple threads, the id
parameter I'm parsing is sometimes wrong. Here is my startup:
for (int i = 0; i < _threadCount; i++)
{
Thread thread = new Thread(() => WorkerThread(i));
thread.Start();
_threads.Add(thread);
}
And my thread 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 mind, this code should create every thread with a unique id
instead of duplicates as seen above.
Compiler info:
Platform target: x64
Target Framework: .NET Framework 4.5
Upvotes: 9
Views: 1903
Reputation: 4119
The problem is that the i
variable refers to the same memory location through the loop's lifetime. Therefore, each thread calls on a variable whose value may change as it is running. The solution is to user a temporary variable int temp = i
. as @Salah Akbari said.
Upvotes: 0
Reputation: 39946
You should be careful about accidentally modifying captured variables like i
after starting the thread, because the i
is shared. The i
variable refers to the same memory location throughout the loop’s lifetime. The solution is to use a temporary variable like this:
for (int i = 0; i < _threadCount; i++)
{
var i1 = i;
Thread thread = new Thread(() => WorkerThread(i1));
thread.Start();
_threads.Add(thread);
}
Read more about Closures here : The Beauty of Closures from (Jon Skeet) and Lambda expressions and captured variables from (Joseph Albahari).
Upvotes: 17