发送带有多个参数的 pthread

Sending pthread with multiple arguments

我正在尝试通过结构发送线程 ID,因为稍后我将不得不发送多个参数。当我执行 data->arg1 = t,并尝试发送数据,然后将线程 ID 存储在 PrintHello 函数中时,我得到了我不应该得到的值。如果我一起取出我的结构并单独发送 t 程序将按预期工作。有人知道为什么会这样吗?

#include <stdio.h>     
#include <stdlib.h>      
#include <unistd.h>     
#include <sys/types.h>   
#include <sys/wait.h>   
#include <errno.h>       
#include <strings.h>    
#include <pthread.h>    

#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   struct data *someData = threadid;
   long threadsID = someData->arg1;
   sleep(2);
   printf("Thread %ld\n", threadsID);
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   pthread_attr_t attr;
   struct myStruct data;
   long t;
   void *status;

   for(t=0; t<NUM_THREADS; t++){
     data.arg1 = t;
     pthread_create(&threads[t], &attr, PrintHello, (void *)&data);        
   }

   pthread_attr_destroy(&attr);
   for ( t=0; t < NUM_THREADS; t++ ) {
      pthread_join(threads[t], &status);

   }
   pthread_exit(NULL);   
}

我在单独的头文件中声明了该结构。

这是因为在线程读取它们的数据之前,结构可能会被更新。 您应该为每个线程分配单独的结构。

试试这个:

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   pthread_attr_t attr;
   struct myStruct data[NUM_THREADS];
   long t;
   void *status;

   for(t=0; t<NUM_THREADS; t++){
     data[t].arg1 = t;
     pthread_create(&threads[t], &attr, PrintHello, &data[t]);        
   }

   pthread_attr_destroy(&attr);
   for ( t=0; t < NUM_THREADS; t++ ) {
      pthread_join(threads[t], &status);

   }
   pthread_exit(NULL);   
}