我读了一本书,它给出了下一个代码:
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);
}
}
以及下一个可能的输出:
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
而且我不明白这怎么可能。我们从主线程开始,创建 4 个线程:tids[0]... tids[3]
. 然后,我们暂停执行(通过 join 指令):主线程会等待tids[0]
会停止执行,tids[0]
会等待tids[1]
等等。
所以输出应该是:
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
我觉得我不明白一些非常基本的东西。谢谢。