使用多个参数发送pthread

时间:2016-03-21 22:59:06

标签: c pthreads

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

#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);   
}

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

1 个答案:

答案 0 :(得分:0)

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

试试这个:

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);   
}
相关问题