【发布时间】:2017-06-20 05:01:35
【问题描述】:
我想通过一个包装对象将我的 for 循环索引传递给 pthread_create 的参数。但是,线程中打印的整数不正确。 我希望下面的代码可以打印出来,没有特定的顺序。
id为0,id为1,id为2,id为3,
但是它会打印这个而不是整数 1,3 永远不会传递到线程中
id为0,id为0,id为0,id为2,
struct thread_arg {
int id;
void * a;
void * b;
}
void *run(void *arg) {
struct thread_arg * input = arg;
int id = input->id;
printf("id is %d, ", id)
}
int main(int argc, char **argv) {
for(int i=0; i<4; i++) {
struct thread_arg arg;
arg.id = i;
arg.a = ...
arg.b = ...
pthread_create(&thread[i], NULL, &run, &arg);
}
}
【问题讨论】:
标签: c multithreading pthreads pthread-join