Atomic Read-Modify-Write: A Single Operation or Two?
For synchronization purposes, atomic read-modify-write (RMW) operations like x.exchange(..., std::memory_order_acq_rel) raise questions regarding their treatment. Are they considered a single operation or two separate operations?
Standard's Perspective
The C standard regards RMW operations as singular entities. This is evident from their naming and implicit in various related language.
Synchronization Implications
In your example:
x.exchange(1, std::memory_order_acq_rel); // Line A y.store(1, std::memory_order_relaxed); // Line B
Consequently, the code is reduced to:
x.store(1, std::memory_order_release); y.store(1, std::memory_order_relaxed);
Since there are no operations between these stores and the corresponding loads in the other thread, the synchronization is effectively disabled. This allows for the possibility of printing 0, 1.
ARM64 Implementation and Implication
ARM64's implementation of x.exchange() raises concerns. However, upon closer examination, it is evident that the implementation aligns with the standard's perspective on a singular RMW operation. The ordering sequence guarantees that the last read value in the RMW is consistent with the write.
Incorrect cppreference Quote
The quoted text from cppreference is inaccurate. RMW operations in C are treated as single operations, and reordering of other operations before or after them is prohibited.
The above is the detailed content of Is Atomic Read-Modify-Write a Single Operation or Two in C ?. For more information, please follow other related articles on the PHP Chinese website!