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