CppMem: Atomics with an Acquire-Release Semantic
Explore atomic operations using acquire-release semantics in C++. Understand the synchronization between atomic stores and loads, memory ordering effects, and how these impact program behavior and optimization. This lesson provides practical examples with CppMem, helping you analyze and verify concurrency scenarios critically.
We'll cover the following...
The synchronization in the acquire-release semantic takes place between atomic operations on the same atomic. This is in contrast to the sequential consistency where we have synchronization between threads. Due to this fact, the acquire-release semantic is more lightweight and, therefore, faster.
Here is the program with acquire-release semantic:
On first glance you will notice that all operations are atomic, so the program is well-defined. But the second glance shows more; the atomic operations on y are attached with the flag std::memory_order_release (line 12) and std::memory_order_acquire (line 16). In contrast to that, the atomic operations on x are annotated with std::memory_order_relaxed (lines 11 and 17), so there are no synchronizations and ordering constraints for x. The answer to the possible values for x and y can only be given by y.
It holds:
y.store(11,std::memory_order_release)synchronizes-withy.load(std::memory_order_acquire)x.store(2000,std::memory_order_relaxed)is