我现在正在学习 POSIX 线程,但我想这只是一个关于多线程的一般问题,所以我希望任何人都可以帮助我。我正在研究的书中有这个例子,它演示了一个竞争条件:
void *thread_main(void *thread_number) {
printf("In thread number %d.\n", *(int *)thread_number);
}
void main() {
int i = 0;
pthread_t thread;
for( i = 0; i < 10; i++ ) {
printf("Creating thread %d.\n");
pthread_create(&thread, 0, thread_main, &i);
printf("Created thread %d.\n");
}
}
关于这个,有几件事我不明白。首先,“在线程号 5 中”。被打印了很多次,即使它不应该在线程号 5 中。在书中,示例显示线程 8 被打印了很多次。我也不明白说的部分*(int *)thread_number
。我尝试将其更改为仅 thread_number,但这只是一遍又一遍地给了我奇怪的数字。
这本书并没有真正解释这一点。有人可以清楚地解释这里发生了什么吗?我不明白为什么它不打印如下内容:
> Creating thread 1.
> In thread number 1.
> Created thread 1.
> Creating thread 2.
> In thread number 2.
> Created thread 2.
我知道这是因为它是多线程的“在线程号 x 中”。部分将在不同的时间出现,但我真的不明白为什么我创建的每个线程都没有 10 个“在线程编号 x”中一行!
~德西