[英]How to check if thread has finished work in C++11 and above?
如何检查线程是否已在C ++ 11及更高版本中完成工作? 我一直在阅读文档,我写了以下代码:
#include <iostream>
#include <thread>
void mythread()
{
//do some stuff
}
int main()
{
std::thread foo(mythread);
if (foo.joinable())
{
foo.join();
//do some next stuff
}
}
joinable
只告诉线程已经开始工作,但我想知道如何编写代码来检查线程是否已完成工作。
例如:
#include <iostream>
#include <thread>
void mythread()
{
//do some stuff
}
int main()
{
std::thread foo(mythread);
if (foo.finishedWork())
{
foo.join();
//do some next stuff
}
}
您可能想要使用std::future
,它提供了更高级别的工具,您可以轻松地检查异步计算是否已完成(也就绪):示例:
void mythread() {
//do some stuff
}
template<typename T>
bool future_is_ready(std::future<T>& t){
return t.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
}
int main()
{
std::future<void> foo = std::async(std::launch::async, mythread);
if (future_is_ready(foo)){
//do some next stuff
}
}
另一方面,您可能认为只使用“安全”(或原子)标志有效:
#include <iostream>
#include <thread>
std::atomic<bool> is_done{false};
void mythread()
{
//do some stuff
......
is_done = true;
}
int main()
{
std::thread foo(mythread);
if (is_done)
{
foo.join();
//do some next stuff
}
.....
if(foo.joinable()) foo.join();
}
但是,它不起作用 。 虽然你认为is_done = true
是你在mythread()
做的最后一件事; 您可能在该范围内创建了一些自动存储持续时间的对象,并且由于这些对象以相反的构造顺序被销毁,因此在设置is_done
之后该线程中仍然会有“一些工作”。
你想要一个未来。 使用std::async
启动线程,并使用wait_for
并使用零秒。 将结果与future_status::ready
进行比较。
您可以使用wait_for
std::future
wait_for
来检查结果是否已存在。 获取异步任务未来的一种简单方法是std::async
。
#include <future>
// ...
// launch task and get result future
auto rf = std::async(std::launch::async, mythread);
// get initial status
auto status = rf.wait_for(std::chrono::nanoseconds(1));
// loop while task is not ready
while(status != std::future_status::ready)
{
// not ready yet, do other stuff here
// 1 nanosecond timeout check
status = rf.wait_for(std::chrono::nanoseconds(1));
}
// we are done...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.