Checking for an Active std::Thread
In the realm of multithreading, understanding if a std::thread is still executing remains crucial. This article delves into practical techniques for platform-independent thread status verification.
Using std::async and std::future
Leveraging std::async and std::future offers a seamless approach for monitoring thread status. Employing wait_for() on the future object provides immediate insight into the thread's state:
#include <future> #include <thread> #include <chrono> #include <iostream> int main() { auto future = std::async(std::launch::async, [] { std::this_thread::sleep_for(3s); return 8; }); auto status = future.wait_for(0ms); if (status == std::future_status::ready) { std::cout << "Thread finished" << std::endl; } else { std::cout << "Thread still running" << std::endl; } }
Using std::promise and std::future
An alternative solution involves leveraging std::promise and std::future:
#include <future> #include <thread> #include <chrono> #include <iostream> int main() { std::promise<bool> p; auto future = p.get_future(); std::thread t([&p] { std::this_thread::sleep_for(3s); p.set_value(true); }); auto status = future.wait_for(0ms); if (status == std::future_status::ready) { std::cout << "Thread finished" << std::endl; } else { std::cout << "Thread still running" << std::endl; } t.join(); }
Using std::atomic
A simpler approach utilizes std::atomic:
#include <thread> #include <atomic> #include <chrono> #include <iostream> int main() { std::atomic<bool> done(false); std::thread t([&done] { std::this_thread::sleep_for(3s); done = true; }); if (done) { std::cout << "Thread finished" << std::endl; } else { std::cout << "Thread still running" << std::endl; } t.join(); }
Using std::packaged_task
In conjunction with std::thread, std::packaged_task offers a more refined solution:
#include <future> #include <thread> #include <chrono> #include <iostream> int main() { std::packaged_task<void()> task([] { std::this_thread::sleep_for(3s); }); auto future = task.get_future(); std::thread t(std::move(task)); auto status = future.wait_for(0ms); if (status == std::future_status::ready) { // ... } t.join(); }
The above is the detailed content of How Can I Check if a `std::thread` is Still Running in C ?. For more information, please follow other related articles on the PHP Chinese website!