When working with std::thread, it is crucial to monitor its execution status for effective thread management. However, the joinable() method is not designed for determining if a thread is still running. Instead, this article presents various platform-independent methods to address this need.
For those comfortable with C 11, std::async and std::future provide a convenient solution. With std::future::wait_for(0ms), you can check the thread's status by examining the returned status value:
#include <future> #include <thread> 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 << "Thread finished" << std::endl; } else { std::cout << "Thread still running" << std::endl; } auto result = future.get(); }
If std::async is not an option, you can employ std::promise to obtain a future object:
#include <future> #include <thread> 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); }); // Check thread status 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(); }
A straightforward approach for C 11 and beyond is to utilize a boolean atomic flag:
#include <atomic> #include <thread> int main() { std::atomic<bool> done(false); std::thread t([&done] { std::this_thread::sleep_for(3s); done = true; }); // Check thread status if (done) { std::cout << "Thread finished" << std::endl; } else { std::cout << "Thread still running" << std::endl; } t.join(); }
Another option is to leverage std::packaged_task, which provides a cleaner alternative to using std::promise:
#include <future> #include <thread> int main() { std::packaged_task<void()> task([] { std::this_thread::sleep_for(3s); }); auto future = task.get_future(); std::thread t(std::move(task)); // Check thread status auto status = future.wait_for(0ms); if (status == std::future_status::ready) { // ... } t.join(); }
These techniques allow you to efficiently monitor the execution status of your std::thread, ensuring proper handling in various scenarios.
The above is the detailed content of How to Effectively Check if a `std::thread` is Still Running in C ?. For more information, please follow other related articles on the PHP Chinese website!