gpt4 book ai didi

c++ - 在 C++ 中使用 pthreads 实现线程池

转载 作者:行者123 更新时间:2023-11-28 03:34:41 25 4
gpt4 key购买 nike

我在设计具有线程池的程序时遇到了问题。

我遇到的主要问题是,当一个线程完成工作时,父线程必须等待 threadId(这是父线程使用 pthread_join 等待线程的方式)。因为我们不知道哪个线程会先完成,所以我无法找到解决问题的编程方法。

感谢任何带有一小段代码的解释。

谢谢。

最佳答案

嗯,我不知道你的设置或要求,但你遇到了 pthread_join() 只等待一个线程的问题,而你实际上想等待任何线程。

因此,最明显的结论是 pthread_join 对您没有帮助。很抱歉陈述显而易见的问题,但我需要建立我的案例:-)

相反,您可能不得不想出另一个主意。例如,您可以等待一个条件变量;在线程退出之前,它会将条件设置为“已退出”。主线程可以等待该条件,遍历线程以找出哪些线程已终止(可能不止一个),并最终重置该条件。条件互斥体通常足以防止竞争。

除了设置条件之外,线程还可以将一些 ID 添加到已退出线程的列表中(您可以使用条件互斥锁来保护该列表),因此主线程只需遍历该列表而不是检查每个线程.

伪代码:

initialize condition variable with status "not exited"
...
...
launch your threads
...
...
while (some threads are still running) do
lock condition variable on "exited"
iterate through threads, remove the ones that have exited
unlock condition variable with new condition "not exited"

在你的话题中:

 ...
do whatever it needs to do
...
...
lock condition variable
unlock condition variable with new condition "exited"
/* end of thread */

关于c++ - 在 C++ 中使用 pthreads 实现线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11342337/

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