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
Passing Multiple Arguments to Threads. When passing multiple arguments to a child thread, the standard approach is to group the arguments within a struct declaration, as shown in Code Listing 6.9. The address of the struct instance gets passed as the arg to pthread_create() .
Example 1 - Thread Argument Passing long taskids[NUM_THREADS]; for(t=0; t<NUM_THREADS; t++) { taskids[t] = t; printf("Creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *) taskids[t]); ... } See the source code.
There are two main ways to return values from a thread, they are: Extend threading. Thread and store data in instance variables. Store data in global variables.
If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With