我现在正在学习线程。我想知道是否可以将变量传递给我的线程。我的任务是创建一个线程并为每个线程分配一个数字(如果愿意的话可以命名)并每 100 毫秒打印该数字。我当前的程序如下:
#define PCHECK(sts,msg) if((sts)!=0){printf("error : %s\n",msg); exit(EXIT_FAILURE)}
#define NB_THREAD 5
void* do_nothing(void* data)
{
int i;
//printf("creation thread %d",(int)data);
while(1)
{
usleep(100000);
printf("thread number : %d \n",data);
}
i = 0;
pthread_exit(NULL);
//exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
int pid, j, status;
pthread_t thread;
int * res;
int stat;
for (j = 0; j < NB_THREAD; j++)
{
stat = pthread_create(&thread, NULL, do_nothing, (void *) j );
if (stat !=0)
{
perror ("pthread_create()");
}
}
for (j = 0; j < NB_THREAD; j++)
{
pthread_join(thread, (void **) &res );
}
return EXIT_SUCCESS;
}
目前唯一打印的数字是 0(数据值)。有人可以指出我哪里出错了,谢谢:)
最佳答案
这里有一些关于如何将参数传递给 pthread 的好例子
[1] https://computing.llnl.gov/tutorials/pthreads/#PassingArguments
关于c - 如何将一个或多个变量传递给新创建的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10663205/