passing for loop index into pthread_create argument object in C

前端 未结 1 384
孤城傲影
孤城傲影 2020-12-22 04:08

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

相关标签:
1条回答
  • 2020-12-22 04:52

    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;
    }
    
    0 讨论(0)
提交回复
热议问题