Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread parameters being changed

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

like image 296
JonasMH Avatar asked Dec 16 '15 18:12

JonasMH


People also ask

How to pass multiple parameters in thread function?

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() .

How to pass arguments in thread c?

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.

How to return thread value?

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.

How to return values from threads in c?

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.


1 Answers

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).

like image 71
Salah Akbari Avatar answered Sep 28 '22 02:09

Salah Akbari