将循环索引传递到C中的pthread_create参数对象中 [英] passing for loop index into pthread_create argument object in C

查看:91
本文介绍了将循环索引传递到C中的pthread_create参数对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过包装对象将for循环的索引传递到pthread_create的参数中.但是,从线程打印的整数不正确. 我希望下面的代码以不特定的顺序打印出来.

I would like to pass my for loop's index into the pthread_create's argument through a wrapper object. However, the printed integer from the thread is incorrect. I expected the below code to print out, in no particular order.

id为0,id为1,id为2,id为3,

id is 0, id is 1, id is 2, id is 3,

但是它将打印此内容,并且永远不会将整数1,3传递给线程

However it prints this instead and integer 1,3 is never passed into a thread

id为0,id为0,id为0,id为2,

id is 0, id is 0, id is 0, id is 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);
 }

}

推荐答案

struct thread_arg在自动存储中,并且其作用域仅存在于for循环内.此外,这些内存中只有1个,您要将相同的一个传递给每个不同的线程.您正在创建一次数据争用,介于两次修改同一对象的ID两次并在工作线程中打印出其ID.此外,一旦for循环存在,该内存就超出范围,并且不再有效.由于您在此处使用线程,因此调度程序可以随意运行您的主线程或任何子线程,因此我希望看到有关打印输出的不一致行为.在将其传递给子线程之前,您需要制作一个struct thread_arg数组或malloc每个数组.

struct thread_arg is in automatic storage, and its scope only exists within the for loop. Furthermore, there's only 1 of these in memory, and you're passing the same one to each different thread. You're creating a data race between modifying this same object's ID 4 different times and printing out its ID in your worker threads. Additionally, once the for loop exists, that memory is out of scope and no longer valid. Since you're using threads here, the scheduler is free to run your main thread or any of your child threads at will, so I would expect to see inconsistent behavior regarding the print outs. You'll need to make an array of struct thread_args or malloc each one before passing it to your child threads.

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

这篇关于将循环索引传递到C中的pthread_create参数对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆