gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:50:24 25 4
gpt4 key购买 nike

据说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( 标准草案),[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.

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

关于c++ - future::wait() 是否与 async() 执行线程的完成同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49146508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com