简体   繁体   中英

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:

Calls to this function do not introduce data races with calls to get_future (but they need not synchronize with each other).

Do set_value() and wait() provide an acquire/release synchronization (or some other form)?

From my reading I believe a is guarnteed to be 2 at the end. Notice the information about the promise itself (emphasis mine):

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

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. You can find more here .

What does mean your qoute about get_future ? It means simply that you can safely call get_future and set_value from different threads and it won't break anything. But also it does not necessarily introduce any memory fences by itself. The only synchronization points that are sure and safe are set_value from std::promise and get from std::future .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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