I read a book, which give the next code:
void *printme(void *id) {
int *i;
i = (int *)id;
printf("Hi. I'm thread %d\n", *i);
return NULL;
}
void main() {
int i, vals[4];
pthread_t tids[4];
void *retval;
for (i = 0; i < 4; i++) {
vals[i] = i;
pthread_create(tids+i, NULL, printme, vals+i);
}
for (i = 0; i < 4; i++) {
printf("Trying to join with tid%d\n", i);
pthread_join(tids[i], &retval);
printf("Joined with tid%d\n", i);
}
}
and the next possible output:
Trying to join with tid0
Hi. I'm thread 0
Hi. I'm thread 1
Hi. I'm thread 2
Hi. I'm thread 3
Joined with tid0
Trying to join with tid1
Joined with tid1
Trying to join with tid2
Joined with tid2
Trying to join with tid3
Joined with tid3
And I don’t understand how is it possible. We start with the main thread, and create 4 threads: tids[0]... tids[3]. Then, we suspend the execution (by the join instruction): the main thread would wait that tids[0] would stop the execution, tids[0] would wait to tids[1] and so on.
So the output should be:
Hi. I'm thread 0
Hi. I'm thread 1
Hi. I'm thread 2
Hi. I'm thread 3
Trying to join with tid0
Trying to join with tid1
Joined with tid0
Trying to join with tid2
Joined with tid1
Trying to join with tid3
Joined with tid2
Joined with tid3
I feel that I don’t understand something really basic. Thanks.
I think what you’re missing is that
pthread_createis very different fromfork. The created thread starts at the supplied function (printme, in this case) and exits as soon as that function returns. Hence, none of the newly created threads ever reaches the secondforloop.