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#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 Using std::promise (with std::thread)
If std::async is not an option, you can employ std::promise to obtain a future object:
#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 Using std::atomic
with std::thread A straightforward approach for C 11 and beyond is to utilize a boolean atomic flag:
#include#include int main() { std::atomic done(false); std::thread t([&done] { std::this_thread::sleep_for(3s); done = true; }); // Check thread status if (done) { std::cout Using std::packaged_task (with std::thread)
Another option is to leverage std::packaged_task, which provides a cleaner alternative to using std::promise:
#include#include int main() { std::packaged_task 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3