如何在 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();
}
But, it 不起作用。当你认为is_done = true
是你做的最后一件事mythread()
;您可能已经创建了一些对象自动存储时长在该范围内,并且由于此类对象以与构造相反的顺序销毁,因此在设置后该线程中仍然会有“一些工作”is_done
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)