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?
launch::async
. – Conventiclestd::future::get()
and you reach the end of main? Does the standard specify that? I ask because when I have seen programs crash when exiting main without joining anstd::thread
(GCC 4.6 or 4.7). – Ringtailstd::thread
when you destroy it, the implementation callsstd::terminate
to abort the program. Usingstd::async
avoids this problem --- it waits for the task to complete. – Medlock