Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

multithreading - passing for loop index into pthread_create argument object in C

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

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...