Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::memory_order — ordering atomic operations

std::memory_order from <atomic> specifies ordering and synchronization for atomic operations. It distinguishes atomicity alone from safely publishing data between threads; incorrectly weakening an order can introduce a data race.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <atomic>
// Examples of explicit ordering:
flag.store(true, std::memory_order::release);
bool value = flag.load(std::memory_order::acquire);

std::memory_order is an enumeration from <atomic> passed to atomic operations. Atomicity concerns the particular object; memory ordering specifies additional guarantees about other reads and writes. relaxed preserves atomicity and that object's modification order but does not itself synchronize access to other data.

release publishes earlier writes, and acquire enables their safe observation: an acquire load synchronizes with a release store when it reads that store's value or reads from the corresponding release sequence. acq_rel combines both directions in a read-modify-write operation. seq_cst, the default for many atomic operations, additionally participates in a single total order of seq_cst operations; it does not automatically order every action in the program.

In C++23, consume describes weaker, data-dependency-based ordering rather than full acquire ordering. Version caveat: the linked evolving draft is not frozen C++23 wording—it currently describes consume as a deprecated equivalent of acquire. For ordinary data publication, use release/acquire rather than relying on consume subtleties.

For store, the permitted orders are relaxed, release, seq_cst; for load in C++23: relaxed, consume, acquire, seq_cst. acq_rel is not valid for a plain load or store. An invalid order violates the operation's requirements; volatile does not replace synchronization.

In the example, the acquire wait returns only after observing a value different from false. It reads the true published by release, so the write to payload happens before its read and the output is 42. notify_one() alone does not publish data. Replacing both orders with relaxed would remove this guarantee and allow a data race on payload.

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);
        ready.notify_one();
    });

    ready.wait(false, std::memory_order::acquire);
    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.

Sources