简体   繁体   中英

pthreads create_pthread() passing multiple arguments

I am following this tutorial on pthreads:

https://computing.llnl.gov/tutorials/pthreads/#Abstract

and there is this example of passing in multiple arguments via a struct:

struct thread_data{
   int  thread_id;
   int  sum;
   char *message;
};

struct thread_data thread_data_array[NUM_THREADS];

int main (int argc, char *argv[])
{
   ...
   thread_data_array[t].thread_id = t;
   thread_data_array[t].sum = sum;
   thread_data_array[t].message = messages[t];
   rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &thread_data_array[t]);
   ...
}

and this example showing how NOT to pass a single argument:

int rc;
long t;

for(t=0; t<NUM_THREADS; t++) 
{
   printf("Creating thread %ld\n", t);
   rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &t);
   ...
}

I don't understand why the last scenario is wrong, because it passes the address of t . However doesn't the first scenario pass the address of the thread_data struct?

In 2nd example t is local variable and its value is changing. Some of the issues are

  • If you pass address of t that address may not be valid after this function terminates.
  • As you are passing address of t each thread will get same address and will try to access /modify same variable resulting race condition.
  • As t is changing in the loop, and you are passing address the same thread will see different values of t .

In 1st case, you are creating separate element for each thread in the array that is passed to the thread. And its declared out of the function, so mostly will be global.

The second example passes the same address to each thread, so each thread would refer to the same variable, which most propaby is not what one wants.

Also (as mentioned by Rohan in his answer ) the memory referenced might become invalid if the main thread exits prior to a thread having been passed this reference to t , as `t ^is atimatic storage to the main thread.

The first example passes a different address to each thread, so each thread would refer to a different variable.

you are creating threads in a for loop and sharing the same global variable by passing address of t. value of t can be modified by other threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM