I have the following code:
#include <iostream> #include <future> #include <chrono> #include <thread> using namespace std; int sleep_10s() { this_thread::sleep_for(chrono::seconds(10)); cout << "Sleeping Done\n"; return 3; } int main() { auto result=async(launch::async, sleep_10s); auto status=result.wait_for(chrono::seconds(1)); if (status==future_status::ready) cout << "Success" << result.get() << "\n"; else cout << "Timeout\n"; }
This is supposed to wait 1 second, print "Timeout", and exit. Instead of exiting, it waits an additional 9 seconds, prints "Sleeping Done", and then segfaults. Is there a way to cancel or detach the future so my code will exit at the end of main instead of waiting for the future to finish executing?
It's simple: You can't. In fact, there is no way of canceling either futures or threads in the standard.
The class template std::future provides a mechanism to access the result of asynchronous operations: An asynchronous operation (created via std::async, std::packaged_task, or std::promise) can provide a std::future object to the creator of that asynchronous operation.
The C++11 standard does not provide a direct way to cancel a task started with std::async
. You will have to implement your own cancellation mechanism, such as passing in an atomic flag variable to the async task which is periodically checked.
Your code should not crash though. On reaching the end of main
, the std::future<int>
object held in result
is destroyed, which will wait for the task to finish, and then discard the result, cleaning up any resources used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With