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?
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.