using std::launch::deferred does not defer the function in std::async

Viewed 49

https://godbolt.org/z/MEsandWGe

Here's the code I'm testing, same as the above godbolt link:

#include <future>
#include <string>
#include <iostream>
#include <chrono>
#include <thread>

using namespace std::chrono_literals;

int main() {
    int v = 0;

    auto a1 = std::async(
        std::launch::async | std::launch::deferred, [&v]() {
            std::cout << "begin 1" << std::endl;
            std::cout << "v = " << v << std::endl;
            std::this_thread::sleep_for(100ms);
            std::cout << "end 1" << std::endl;
    });

    auto a2 = std::async(
        std::launch::async | std::launch::deferred, [&v]() {
            std::cout << "begin 2" << std::endl;
            std::this_thread::sleep_for(200ms);
            v = 123;
            std::cout << "end 2" << std::endl;
    });

    a2.wait();
    // My understanding is a1 does not run until here?
    // thus v should print 123 instead of 0 ?
    a1.wait();

    return 0;
}

If I remove the async policy, it works as expected.

The question is, why do I see a1 running concurrently with a2 and see v printed as 0? Does the async policy affect the behavior of deferred?

1 Answers

std::launch::async | std::launch::deferred means that std::async can choose which of the two policies is selected. It is implementation defined which one is used but it looks like your standard library chooses async rather than deferred.

Related