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

前端 未结 3 1879
广开言路
广开言路 2020-11-29 03:47

I have the following code:

#include 
#include 
#include 
#include 

using namespace std;

int sleep         


        
3条回答
  •  悲&欢浪女
    2020-11-29 03:56

    Here a simple example using an atomic bool to cancel one or multiple future at the same time. The atomic bool may be wrapped inside a Cancellation class (depending on taste).

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int long_running_task(int target, const std::atomic_bool& cancelled)
    {
        // simulate a long running task for target*100ms, 
        // the task should check for cancelled often enough!
        while(target-- && !cancelled)
            this_thread::sleep_for(chrono::milliseconds(100));
        // return results to the future or raise an error 
        // in case of cancellation
        return cancelled ? 1 : 0;
    }
    
    int main()
    {
        std::atomic_bool cancellation_token;
        auto task_10_seconds= async(launch::async, 
                                    long_running_task, 
                                    100, 
                                    std::ref(cancellation_token));
        auto task_500_milliseconds = async(launch::async, 
                                           long_running_task, 
                                           5, 
                                           std::ref(cancellation_token));
    // do something else (should allow short task 
    // to finish while the long task will be cancelled)
        this_thread::sleep_for(chrono::seconds(1));
    // cancel
        cancellation_token = true;
    // wait for cancellation/results
        cout << task_10_seconds.get() << " " 
             << task_500_milliseconds.get() << endl;
    }
    

提交回复
热议问题