[英]How to check the status of detached thread in C++11?
我已经尝试寻找解决方案的多种方法,但到目前为止找不到合适的方法。
我正在使用分离线程,因为我不希望我的主线程等待/阻塞新的子线程,因为它还有许多其他重要的事情要做。
我创建一个线程如下:
std::thread rsync_t(&PreCompile::RunPreCompileThr, obj, arg1, arg2);
rsync_t.detach();
现在,目标是定期检查这个分离的线程是否处于活动状态并正在运行。
我尝试了未来/承诺和异步方式来做到这一点,但它需要 .get(),它类似于 join(),这是我不想要的。
有什么建议可以做到这一点吗?
提前致谢。
一旦你分离了一个线程,那么你已经明确地说“我不需要等待这个线程完成”。 这通常是因为线程永远不会结束,并且一直运行到程序结束。
在任何情况下, std::thread
都没有提供一种机制来轮询以查看线程是否已完成而无需等待。 为此,无论线程是否分离,您都需要使用替代机制。
一种选择是使用std::async(std::launch::async, func)
启动线程并使用返回的未来检查线程是否仍在运行。
auto future=std::async(std::launch::async,thread_func);
bool thread_is_still_running=future.wait_for(std::chrono::seconds(0))!=std::future_status::ready;
如果您使用此选项,则您将需要保留future
对象(例如,将其存储在长期存在的std::vector
或全局变量中),因为其析构函数将等待线程完成。
或者,您可以使用std::mutex
和布尔标志,或在线程退出之前从线程内设置的std::atomic<bool>
来指示线程何时完成。
std::atomic<bool> done=false;
void thread_func(){
do_stuff();
done=true;
}
如果detach
std::thread
,则会丢失std::thread
对象提供的通信通道:
https://en.cppreference.com/w/cpp/thread/thread/detach
调用 detach
*this
不再拥有任何线程。
如果以后想以任何方式与分离的线程通信,则需要手动进行。 std::thread
在detach
后无法再帮助您。
我正在使用分离线程,因为我不希望我的主线程等待/阻塞新的子线程,因为它还有许多其他重要的事情要做。
正确的解决方案可能不涉及detach
。 您不需要detach
以使线程并行运行,当std::thread
构造函数返回时,它已经并行运行。 只需保持std::thread
对象处于活动状态并通过它进行查询,并且仅在线程实际应该完成/结束时才调用join
。 也就是说, std::thread
只提供joinable
,它只在join
之后更改,因此它不提供您需要的信息(您的代码以某种形式“完成”)。
使用std::async
,您可以选择从未来检索任务状态。 没有必要使用get()
。
https://en.cppreference.com/w/cpp/thread/future/wait_for
auto status = future.wait_for(std::chrono::milliseconds(1));
if (status == std::future_status::ready) {
// Thread has finished
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.