Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to cancel/detach a future in C++11?

Tags:

c++

c++11

future

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?

like image 994
m42a Avatar asked Aug 23 '12 07:08

m42a


People also ask

How can we prevent future STDS?

It's simple: You can't. In fact, there is no way of canceling either futures or threads in the standard.

What is STD future?

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.


1 Answers

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.

like image 171
Anthony Williams Avatar answered Sep 19 '22 15:09

Anthony Williams