将for循环索引传递到C中的pthread_create参数对象
我想通过包装器对象将for循环的索引传递到pthread_create的参数中。但是,线程中打印的整数不正确。 我希望下面的代码打印出来,没有特别的顺序 id为0,id为1,id为2,id为3 但是,它会打印这个,整数1,3永远不会传递到线程中 id为0,id为0,id为0,id为2将for循环索引传递到C中的pthread_create参数对象,c,multithreading,pthreads,pthread-join,C,Multithreading,Pthreads,Pthread Join,我想通过包装器对象将for循环的索引传递到pthread_create的参数中。但是,线程中打印的整数不正确。 我希望下面的代码打印出来,没有特别的顺序 id为0,id为1,id为2,id为3 但是,它会打印这个,整数1,3永远不会传递到线程中 id为0,id为0,id为0,id为2 struct thread\u参数{ int-id; 无效*a; 无效*b; } void*run(void*arg){ struct thread_arg*input=arg; int id=输入->id; pr
struct thread\u参数{
int-id;
无效*a;
无效*b;
}
void*run(void*arg){
struct thread_arg*input=arg;
int id=输入->id;
printf(“id为%d,”,id)
}
int main(int argc,字符**argv){
对于(int i=0;istruct thread_arg
处于自动存储中,其作用域仅存在于for
循环中。此外,内存中只有一个这样的循环,并且您正在将相同的循环传递给每个不同的线程。您正在创建一个数据竞争,在不同时间修改同一对象的ID 4次和打印出其ID i之间n您的工作线程。此外,一旦for
循环存在,该内存将超出范围,不再有效。由于您在此处使用线程,调度程序可以随意运行主线程或任何子线程,因此我希望看到打印输出的行为不一致。您需要创建一个struct thread\u arg
s或malloc,然后将其传递给子线程
#define NUM_THREADS 4
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) {
struct thread_arg args[NUM_THREADS];
for(int i=0; i<NUM_THREADS; i++) {
args[i].id = i;
args[i].a = ...
args[i].b = ...
pthread_create(&thread[i], NULL, &run, &args[i]);
}
// probably want to join on threads here waiting on them to finish
return 0;
}
#定义NUM_线程4
结构线程参数{
int-id;
无效*a;
无效*b;
}
void*run(void*arg){
struct thread_arg*input=arg;
int id=输入->id;
printf(“id为%d,”,id)
}
int main(int argc,字符**argv){
结构线程参数[NUM_THREADS];
对于(int i=0;i
#define NUM_THREADS 4
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) {
struct thread_arg args[NUM_THREADS];
for(int i=0; i<NUM_THREADS; i++) {
args[i].id = i;
args[i].a = ...
args[i].b = ...
pthread_create(&thread[i], NULL, &run, &args[i]);
}
// probably want to join on threads here waiting on them to finish
return 0;
}