Search code examples
c++c++11synchronizationatomicmemory-model

Does future::wait() synchronize-with completion of the thread of execution by async()?


It's said that thread::join() synchronizes-with completion of the corresponding thread of execution. I'm wondering whether the same applies to async() and future::wait(). So for example:

std::atomic_int v(0);
std::async(
  std::launch::async,
  [&v] { v.fetch_add(1, std::memory_order_relaxed); }
).wait();
assert(v.load(std::memory_order_relaxed) == 1);

The assert() will never fail.


Solution

  • Straight from N3337 ( standard draft), [futures.async]/5 with my emphasis:

    Synchronization: Regardless of the provided policy argument,

    • the invocation of async synchronizes with ([intro.multithread]) the invocation of f. [ Note: This statement applies even when the corresponding future object is moved to another thread. — end note ]; and

    • the completion of the function f is sequenced before ([intro.multithread]) the shared state is made ready. [ Note: f might not be called at all, so its completion might never happen. — end note ]

    If the implementation chooses the launch::async policy,

    • a call to a waiting function on an asynchronous return object that shares the shared state created by this async call shall block until the associated thread has completed, as if joined ([thread.thread.member]);

    • the associated thread completion synchronizes with ([intro.multithread]) the return from the first function that successfully detects the ready status of the shared state or with the return from the last function that releases the shared state, whichever happens first.

    So referring to your question this means that yes, the assertion will never fail.