【问题标题】:passing for loop index into pthread_create argument object in C将 for 循环索引传递给 C 中的 pthread_create 参数对象
【发布时间】: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


    【解决方案1】:

    struct thread_arg是自动存储的,它的作用域只存在于for循环内。此外,内存中只有 1 个,并且您将相同的一个传递给每个不同的线程。您在 4 次不同时间修改同一对象的 ID 和在工作线程中打印出其 ID 之间创建了数据竞争。此外,一旦存在for 循环,该内存就会超出范围并且不再有效。由于您在这里使用线程,调度程序可以随意运行您的主线程或任何子线程,因此我希望看到有关打印输出的不一致行为。在将其传递给子线程之前,您需要创建一个 struct thread_args 或 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-12
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 2023-03-31
      • 2016-01-07
      • 1970-01-01
      • 2017-10-12
      • 2018-02-15
      相关资源
      最近更新 更多