gpt4 book ai didi

c - 帮助基本线程概念/竞争条件

转载 作者:行者123 更新时间:2023-12-02 07:56:55 25 4
gpt4 key购买 nike

我现在正在学习 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 中”一行!

~德西

最佳答案

首先 *(int *)thread_number 是指针的东西——当你只有 thread_number 时,“奇怪的数字”是 main 函数中指向“i”的指针地址(除非我我错了,对于单次程序运行,它们应该都是相同的数字(因此 10 个线程中的每一个都应该具有相同的“线程编号 [number]”)。

您需要了解,这些是重复 5 的指针才有意义 - 每个线程都使用来自 main 函数的相同底层 i - 它不会被复制到每个新线程,所以当 i 在 main 函数中递增时,这反射(reflect)在 thread_main 函数中的 thread_number。

最后一个难题是每个新线程的设置时间和上下文切换(更改实际运行的线程)不是立即的,因此在您的情况下,for 循环在新创建的线程之前运行 5 次实际运行(在本书的例子中,for 循环在上下文切换之前运行了 8 次),然后每个线程查看相同的底层 i 值,现在是 5。

关于c - 帮助基本线程概念/竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/416273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com