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