Can I use std::async without waiting for the future limitation?

后端 未结 4 772
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 14:47

High level
I want to call some functions with no return value in a async mode without waiting for them to finish. If I use std::async the future object

4条回答
  •  借酒劲吻你
    2020-11-27 15:26

    You can move the future into a global object, so when the local future's destructor runs it doesn't have to wait for the asynchronous thread to complete.

    std::vector> pending_futures;
    
    myResonseType processRequest(args...)
    {
        //Do some processing and valuate the address and the message...
    
        //Sending the e-mail async
        auto f = std::async(std::launch::async, sendMail, address, message);
    
        // transfer the future's shared state to a longer-lived future
        pending_futures.push_back(std::move(f));
    
        //returning the response ASAP to the client
        return myResponseType;
    
    }
    

    N.B. This is not safe if the asynchronous thread refers to any local variables in the processRequest function.

    While using std::async (at least on MSVC) is using an inner thread pool.

    That's actually non-conforming, the standard explicitly says tasks run with std::launch::async must run as if in a new thread, so any thread-local variables must not persist from one task to another. It doesn't usually matter though.

提交回复
热议问题