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

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

I have the following code:

#include 
#include 
#include 
#include 

using namespace std;

int sleep         


        
3条回答
  •  [愿得一人]
    2020-11-29 04:03

    I know this is an old question, but it still comes up as the top result for "detach std::future" when searching. I came up with a simple template based approach to handle this:

    template 
    std::future startDetachedFuture(FUNCTION_TYPE func) {
        std::promise pro;
        std::future fut = pro.get_future();
    
        std::thread([&func](std::promise p){p.set_value(func());},
                    std::move(pro)).detach();
    
        return fut;
    }
    

    and you use it like so:

    int main(int argc, char ** argv) {
        auto returner = []{fprintf(stderr, "I LIVE!\n"); sleep(10); return 123;};
    
        std::future myFuture = startDetachedFuture(returner);
        sleep(1);
    }
    

    output:

    $ ./a.out 
    I LIVE!
    $
    

    If myFuture goes out of scope and is destructed, the thread will carry on doing whatever it was doing without causing problems because it owns the std::promise and its shared state. Good for occasions where you only sometimes would prefer to ignore the result of a computation and move on (my use case).

    To the OP's question: if you get to the end of main it will exit without waiting for the future to finish.

提交回复
热议问题