如何檢查std :: thread是否仍在運行(cross-platform)
{ std :: this_thread :: sleep_for(3s); 返回8; }); //檢查線程狀態 自動狀態= future.wait_for(0ms); if(status == std :: future_status ::準備就緒){ std :: cout
If std::async is not an option, you can employ std::promise to obtain a future object:
#include#include int main() { auto future = std::async(std::launch::async, [] { std::this_thread::sleep_for(3s); return 8; }); // Check thread status auto status = future.wait_for(0ms); if (status == std::future_status::ready) { std::cout 使用std :: atomic 與std :: thread C 11及以後的一種簡單的方法是利用布爾原子flag:
{ std :: this_thread :: sleep_for(3s); 完成= true; }); //檢查線程狀態 如果(完成){ std :: cout Using std::packaged_task (with std::thread)#include#include int main() { std::promise p; auto future = p.get_future(); std::thread t([&p] { std::this_thread::sleep_for(3s); p.set_value(true); }); // Check thread status auto status = future.wait_for(0ms); if (status == std::future_status::ready) { std::cout Another option is to leverage std::packaged_task, which provides a cleaner alternative to using std::promise:#include #include int main(){ std :: packaged_task 任務([] { std :: this_thread :: sleep_for(3s); }); auto future = task.get_future(); std ::線程t(std :: move(task)); //檢查線程狀態 自動狀態= future.wait_for(0ms); if(status == std :: future_status ::準備就緒){ // ... } T.Join(); } [&& && && && &&華
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3