【发布时间】:2019-01-31 11:17:02
【问题描述】:
我正在用 C++ 编写一个服务器,它由一个接受传入请求的主线程组成,然后生成一个新的 std::thread 对象来处理响应它的任务。
这个 std::thread 对象进入一个线程列表,我想像这样定期清理这个列表:
For each thread in the list:
If the thread has finished executing:
Call join on the thread
Remove the thread object from the list
现在的挑战是如何确定这个线程(它正在执行一个 void 函数)是否已经结束。 joinable() 函数不起作用,因为它返回真正的中间执行以及之后,我只希望我的主线程在完成后调用 join(),否则它将挂起并等待该子线程串行而不是并行执行。
【问题讨论】:
-
标准 C++ 中没有办法;解决方案是特定于平台的。在 Windows 中使用
if (WaitForSingleObject(thread.native_handle(), 0) == WAIT_OBJECT_0)。
标签: c++ multithreading