如何检查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