Reputation: 93
fetch_xx are RWM operations, but in the following code:
int item_index=count.fetch_sub(1,std::memory_order_acquire);
I know the load of fetch_sub is acquire, but which memory order is the store operation? is default memory_order_seq_cst?
compare_and_swap and exchange are same question
Upvotes: 0
Views: 181
Reputation: 58518
For the atomic read-modify-write instructions, std::memory_order_acquire
means that the load is acquire and the store is relaxed. Similarly, std::memory_order_release
means that the load is relaxed and the store is release.
The idea is that you can do something like
// non-critical code
if (busy.fetch_add(1, std::memory_order_acquire) == 0) {
// critical section
}
The load of 0 is what proves that this thread now owns the lock. Thus the load needs to be acquire so that the critical section does not get reordered before the lock is taken. But the store does not need to be ordered in any particular way with surrounding memory accesses. It still remains atomic with the load, of course, but it would be okay if the non-critical code were reordered after the fetch_add
.
This is stated in the standard only by omission; [atomics.order p1] says that memory_order_acquire
performs an acquire operation, and does not say that it performs a release operation, whereas it says that memory_order_acq_rel
does both. And the sequentially consistent operations are only those for which memory_order_seq_cst
is explicitly specified. The atomic nature of the RMW is specified by p10 which promises that the read returns the value in the modification order immediately preceding the value that is to be stored.
There isn't any way to get a load that is acquire but not seq_cst
together with a sequentially consistent store. I can't think of a case where you would want that, anyway.
If you need either half to be sequentially consistent then you have to upgrade the whole operation to seq_cst
.
Note that in general when you have an atomic RMW, it is possible for other memory operations to be reordered in between the load and the store, if their memory orderings otherwise allow this. See For purposes of ordering, is atomic read-modify-write one operation or two?
Upvotes: 1