CKTIS / C++
Atomic memory orders
Constants of type std::memory_order control synchronization and ordering for atomic operations. Learn how relaxed, release, acquire, acq_rel, and seq_cst differ, and how an atomic flag can safely publish ordinary data.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <atomic>
a.load(std::memory_order_acquire);
a.store(value, std::memory_order_release);
a.fetch_add(1, std::memory_order_relaxed);
a.exchange(value, std::memory_order_acq_rel);
a.load(std::memory_order_seq_cst);Constants from <atomic> of type std::memory_order select ordering rules; they do not make ordinary variables atomic. Names such as std::memory_order_relaxed correspond to values such as std::memory_order::relaxed. These rules apply to C++23; eel.is hosts an evolving draft, not a frozen C++23 publication.
std::memory_order_relaxed preserves atomicity but does not itself synchronize access to other data between threads. std::memory_order_release can publish earlier writes. std::memory_order_acquire synchronizes with a release operation on the same atomic object when it reads that operation's value or a value from its release sequence. Merely using the two names is insufficient.
std::memory_order_acq_rel combines acquire and release in a read-modify-write operation such as exchange. std::memory_order_seq_cst supplies the applicable acquire/release properties plus a single total order of seq_cst operations. It neither repairs data races nor automatically includes weaker operations in that order.
For load, the valid choices among these five constants are relaxed, acquire, and seq_cst; for store, they are relaxed, release, and seq_cst. acq_rel is not valid for a plain load or store. These methods default to seq_cst. Weakening an order requires a correctness argument, not just a speed measurement.
In the example, the acquire read of true synchronizes with the release store, so payload = 42 happens before its read. Replacing both orders with relaxed would remove that guarantee and cause a data race on payload. The loop busy-waits; the output on completion is fixed, but the waiting time has no fixed bound.
Examples
#include <atomic>
#include <iostream>
#include <thread>
int main() {
int payload = 0;
std::atomic<bool> ready{false};
std::thread producer([&] {
payload = 42;
ready.store(true, std::memory_order_release);
});
while (!ready.load(std::memory_order_acquire)) {
std::this_thread::yield();
}
std::cout << payload << '\n';
producer.join();
}
Result
42
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.