简体   繁体   English

std::promise::set_value() 和 std::future::wait() 是否提供 memory 围栏?

[英]Do std::promise::set_value() and std::future::wait() provide a memory fence?

If I do the following:如果我执行以下操作:

std::promise<void> p;
int a = 1;

std::thread t([&] {
  a = 2;
  p.set_value();
});

p.get_future().wait();

// Is the value of `a` guaranteed to be 2 here?

cppreference has this to say about set_value() , but I am not sure what it means: cppreferenceset_value()有这样的说法,但我不确定这意味着什么:

Calls to this function do not introduce data races with calls to get_future (but they need not synchronize with each other).对此 function 的调用不会与对 get_future 的调用引入数据竞争(但它们不需要相互同步)。

Do set_value() and wait() provide an acquire/release synchronization (or some other form)? set_value()wait()是否提供获取/释放同步(或其他形式)?

From my reading I believe a is guarnteed to be 2 at the end.从我的阅读来看,我相信a最后肯定是 2。 Notice the information about the promise itself (emphasis mine):注意有关promise 本身的信息(强调我的):

The promise is the "push" end of the promise-future communication channel: the operation that stores a value in the shared state synchronizes-with (as defined in std::memory_order) the successful return from any function that is waiting on the shared state (such as std::future::get). promise 是 promise-future 通信通道的“推送”端:在共享 state 中存储值的操作与(如 std::memory_order 中定义的)同步从正在等待共享的任何 ZC1C425268E683894F14Z 的成功返回state(如 std::future::get)。 Concurrent access to the same shared state may conflict otherwise: for example multiple callers of std::shared_future::get must either all be read-only or provide external synchronization.否则,对同一共享 state 的并发访问可能会发生冲突:例如 std::shared_future::get 的多个调用者必须要么都是只读的,要么提供外部同步。

Of course I encourage you to read what it means that something synchronizes-with.当然,我鼓励您阅读某些内容同步的含义。 For this situation it means that set_value is seen as inter-thread happening-before and therefore from what I get writing a is a visible side effect.对于这种情况,这意味着set_value被视为线程间发生之前,因此从我得到的写a是可见的副作用。 You can find more here .你可以在这里找到更多。

What does mean your qoute about get_future ?你对get_future的看法是什么意思? It means simply that you can safely call get_future and set_value from different threads and it won't break anything.这意味着您可以安全地从不同的线程调用get_futureset_value并且它不会破坏任何东西。 But also it does not necessarily introduce any memory fences by itself.但它本身也不一定会引入任何 memory 围栏。 The only synchronization points that are sure and safe are set_value from std::promise and get from std::future .唯一确定且安全的同步点是来自std::promiseset_value和来自get std::future的同步点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM