gpt4 book ai didi

c - Posix 线程在其他线程退出后挂起?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:37 24 4
gpt4 key购买 nike

3 个线程:

pthread_create(&thread1, 
&NULL,
Thread1,
NULL);
pthread_create(&thread2,
&NULL,
Thread2,
NULL);
pthread_create(&thread3,
&NULL,
Thread3,
NULL);

printf("\n\nThreads Created\n");

pthread_join(thread1,0);
printf("Joined Thread1\n");

pthread_join(thread2,0);
printf("Joined Thread2\n");

pthread_join(thread3,0);
printf("Joined Thread3\n");

这 3 个线程运行了一段时间,根据控制台的输出,似乎在工作。

最终,线程 1 和 2 在完成工作后死亡(显示为 maint()“Joined Thread 1/2”的输出显示正确)

现在,线程 3 仍有一些工作要做,看起来不错。然后,接近处理它的最后几项时,它“看起来”线程 3 刚刚挂起。它将向控制台打印一些内容,甚至不会完成句子。

线程 3 有一个小的 sleep 、互斥量的锁定和解锁(线程 1 和 2 正在使用)和有条件的等待。似乎没有条件等待,因为我在调用之前直接打印了一些东西,但没有看到。

好像是 sleep ,放弃了CPU,然后就再也回不来了......?

还有其他可能性或原因吗?

有什么解决办法吗?

谢谢。

最佳答案

正如在评论/聊天中确认的那样,问题不是线程 3 没有打印任何输出,而是输出被 printf() 缓冲。

你可以使用 fflush()刷新它,或使用 \n 刷新 stdout,因为它通常是行缓冲的。

或者您可以使用 setbuf() 完全禁用缓冲.

setbuf(stdout, NULL);

关于c - Posix 线程在其他线程退出后挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24225411/

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