How do I make a function asynchronous in C++?

后端 未结 7 555
别跟我提以往
别跟我提以往 2021-02-02 11:21

I want to call a function which will be asynchronous (I will give a callback when this task is done).

I want to do this in single thread.

7条回答
  •  执笔经年
    2021-02-02 12:08

    As of C++11, plain c++ does have a concept of threads, but the most concise way to call a function asynchronously is to use the C++11 async command along with futures. This ends up looking a lot like the way you'd do the same thing in pthreads, but it's 100% portable to all OSes and platforms:

    Say your function has a return value... int = MyFunc(int x, int y)

    #include 
    

    Just do:

    // This function is called asynchronously
    std::future EventualValue = std::async(std::launch::async, MyFunc, x, y); 
    

    Catch? How do you know when it's done? (The barrier.)

    Eventually, do:

    int MyReturnValue = EventualValue.get(); // block until MyFunc is done
    

    Note it's easy to do a parallel for loop this way - just create an array of futures.

提交回复
热议问题