C 变量作为pthreads中的参数
我已经编写了一个程序来创建线程数。该数字可以作为命令行参数传递,或默认值为5。我面临的问题是打印作为参数传递给pthread writer函数的线程号 以下是我的节目:C 变量作为pthreads中的参数,c,pthreads,C,Pthreads,我已经编写了一个程序来创建线程数。该数字可以作为命令行参数传递,或默认值为5。我面临的问题是打印作为参数传递给pthread writer函数的线程号 以下是我的节目: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> void *writerThread(void *args) { int id = *((int *)args);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
void *writerThread(void *args)
{
int id = *((int *)args);
printf("In thread %d\n", id);
}
int main(int argc, char *argv[])
{
int numThreads;
if(argc != 2)
numThreads = 5;
else
numThreads = atoi(argv[1]);
pthread_t *tId = (pthread_t*) malloc(sizeof(pthread_t) * numThreads);
int i;
for(i = 0; i < numThreads; i++)
{
pthread_create(&tId[i], NULL , writerThread, &i);
}
// wait for threads
for(i = 0; i < numThreads; i++)
pthread_join(tId[i], NULL);
if(tId)
free(tId);
return 0;
}
为什么0和2会出现两次?
如果您有任何帮助,我们将不胜感激。当您创建线程时
pthread_create(&tId[i], NULL , writerThread, &i);
i
继续它的生命。。。因此,当您在线程中打印*(int*)args
时。您将获得在主函数中不断使用和更改的i
的当前值
您可能希望分配一个包含线程id的整数数组,并在线程创建期间存储该id
int tids[numThreads];
for(i = 0; i < numThreads; i++) {
tids[i] = i;
pthread_create(&tId[i], NULL , writerThread, &tids[i]);
}
inttids[numThreads];
对于(i=0;i
这样,每个线程都有一个指向它自己的个人数据的参数(在这种情况下是一个整数)。为了补充,在向线程例程传递一个小整数的特殊情况下,您可以强制转换为intptr\t
键入该参数,然后编码:
void *writerThread(void *args) {
int id = (int)((intptr_t)arg);
printf("In thread %d\n", id);
}
然后
因为在
malloc
失败的不太可能的情况下,您的代码会显示,因为pthread\u create
的第一个参数应该是某个pthread\u t
的有效地址,所以您必须确保每个线程都有自己的单独变量,因为无法保证指向的数据与您预期的相同当线程开始运行时。因此,您需要一个线程号数组,并向每个线程传递不同的条目(int thr_num[numThreads];…{thr_num[i]=i;pthread_create(…,&thr_num[i]))
。而且,除非您认为线程的数量会非常高,否则我会使用pthread\u t
结构的VLA,甚至是固定大小的数组-类似于前面建议的thr\u num
数组。或者创建一个包含pthread\u t
和int
的结构数组。就好像这个问题没有得到足够的回答一样lready!您标记为重复的几个答案没有提到intptr\t
cast技巧(这是特定于向线程例程传递整数的情况)。因此我认为我的答案不值得您投反对票。
void *writerThread(void *args) {
int id = (int)((intptr_t)arg);
printf("In thread %d\n", id);
}
for(i = 0; i < numThreads; i++) {
pthread_create(&tId[i], NULL , writerThread, (void*)((intptr_t)i));
}
pthread_t *tId = malloc(sizeof(pthread_t) * numThreads);
if (tId == NULL) { perror("malloc tId"); exit(EXIT_FAILURE); };