[英]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.