my code is below:
void f1() {
    for (int i = 0; i < 1000; ++i) {
        std::cout << "f1: " << i << std::endl;
    }
}
void f2() {
    for (int i = 0; i < 10; ++i) {
        std::cout << "f2: " << i << std::endl;
    }
}
auto fz = []() {
        auto l_future = std::async(std::launch::async, f1);
        auto r_future = std::async(std::launch::async, f2);
        while (!is_ready(r_future)) {}
        std::cout << "right done" << std::endl;
    };
fz();
std::cout << "one of task done" << std::endl;
the result is that "right done" is printed but fz() is not finished."one of task done" is printed until the f1 is finished. Now i want to print "one of task done" before f1 is finished.How can i do?
std::async() does following things, It automatically creates a thread (Or picks from internal thread pool) and a promise object for us. Then passes the std::promise object to thread function and returns the associated std::future object.
As the name indicates, C++ async is a function template fn, which takes functions or function objects as arguments (basically called callbacks) and runs them asynchronously. It returns the std:: the future object which is used to keep the result of the above function. The result is stored in the shared state.
Just do: // This function is called asynchronously std::future<int> EventualValue = std::async(std::launch::async, MyFunc, x, y);
From this std::async reference:
If the
std::futureobtained fromstd::asyncis not moved from or bound to a reference, the destructor of thestd::futurewill block at the end of the full expression until the asynchronous operation completes
When the lambda ends and the two std::future objects are destructed, the destruction of l_future will block until the function f1 returns.
Your code hangs in [1] line
auto fz = []() {
        auto l_future = std::async(std::launch::async, f1);
        auto r_future = std::async(std::launch::async, f2);
        while (!is_ready(r_future)) {}
        std::cout << "right done" << std::endl;
        // [1]
    };
because dtor of future waits for a result.
You can return future from your lambda, and after cout call get to wait for a result i.e. until f1 task is completion:
auto fz = []() {
        auto l_future = std::async(std::launch::async, f1);
        auto r_future = std::async(std::launch::async, f2);
        while (!is_ready(r_future)) {}
        std::cout << "right done" << std::endl;
        return l_future; // move future outside lambda
    };
auto fut = fz();
std::cout << "one of task done" << std::endl;
fut.get();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With