passing for loop index into pthread_create argument object in C

随声附和 提交于 2019-12-29 09:57:30

问题


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 is 0, id is 1, id is 2, id is 3,

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

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

}


回答1:


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


来源:https://stackoverflow.com/questions/42013821/passing-for-loop-index-into-pthread-create-argument-object-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!