Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::atomic: atomic access to a shared value

std::atomic provides indivisible loads, stores, and read-modify-write operations on one object and lets code specify memory ordering.

Version: C++23

Syntax

template<class T>
struct atomic; // T: non-cv, trivially copyable, copy/move constructible and assignable

// common selected operations
T load(std::memory_order order = std::memory_order_seq_cst) const noexcept;
void store(T desired, std::memory_order order = std::memory_order_seq_cst) noexcept;
bool is_lock_free() const noexcept;
T exchange(T desired, std::memory_order order = std::memory_order_seq_cst) noexcept;

// applicable numeric and pointer specializations additionally provide:
T fetch_add(/* difference type */ operand,
    std::memory_order order = std::memory_order_seq_cst) noexcept;

std::atomic<T> from <atomic> provides the common load, store, exchange, and compare-exchange operations on one value; the default order is std::memory_order_seq_cst. fetch_add is not part of every atomic<T> interface: it is supplied only by applicable specializations, including numeric and pointer specializations. For the primary template, T must be trivially copyable, copy- and move-constructible, copy- and move-assignable, and not cv-qualified. std::atomic::load performs an atomic read and does not permit release or acq_rel ordering; std::atomic::store performs an atomic write and does not permit consume, acquire, or acq_rel. On an applicable specialization, std::atomic::fetch_add is one read-modify-write operation and returns the value immediately before the addition, while std::atomic::is_lock_free reports whether this object’s operations are lock-free.

Atomicity of one variable does not make a whole protocol atomic. With weaker orders, the synchronization relation must be proven; a wrong mix of relaxed, acquire, and release can be logically incorrect even without a data race.

An atomic is not automatically a lock-free replacement for a mutex; query is_lock_free(). Atomic objects are not copied like ordinary values. compare_exchange_weak may fail spuriously, so it is normally used in a loop, and on failure it updates the expected value.

Examples

#include <atomic>
#include <iostream>

int main() {
    std::atomic<int> value{3};
    value.fetch_add(4);
    std::cout << value.load() << '\n';
}

Result

7

std::atomic → 7

Sources