future::wait() 是否与 async() 执行线程的完成同步?

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

据说 thread::join() 与相应执行线程的完成同步。我想知道这是否同样适用于 async()future::wait()。例如:

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);

assert() 永远不会失败。

直接来自 N3337( standard draft), [futures.async]/5 我强调:

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.

所以提到你的问题,这意味着是的,断言永远不会失败。