Skip to content

std::atomic (C++11)

In a Nutshell

A template class that guarantees read and write operations are indivisible, preventing data races when multiple threads access the same variable concurrently.

Header File

cpp
#include <atomic>

Core API Cheat Sheet

OperationSignatureDescription
Constructoratomic() noexceptDefault construction (value is uninitialized)
AssignmentT operator=(T) noexceptAtomically write the selected value
ReadT operator T() const noexceptAtomically read and return the current value
Storevoid store(T, order = memory_order::seq_cst) noexceptAtomic write
LoadT load(order = memory_order::seq_cst) const noexceptAtomic read
ExchangeT exchange(T, order = memory_order::seq_cst) noexceptAtomically replace the old value and return the old value
Compare Exchangebool compare_exchange_weak(T&, T, order, order) noexceptWeak CAS, may spuriously fail
Compare Exchangebool compare_exchange_strong(T&, T, order, order) noexceptStrong CAS, only fails on a true mismatch
Atomic AddT fetch_add(T, order = memory_order::seq_cst) noexceptAtomically add and return the old value (integer/pointer)
Lock-free Checkbool is_lock_free() const noexceptCheck if the current type is implemented in a lock-free manner

Minimal Example

Expand (23 lines)Collapse
cpp
#include <atomic>
#include <thread>
#include <iostream>

std::atomic<int> counter{0};

void task() {
    for (int i = 0; i < 1000; ++i) {
        // Atomically increment counter by 1
        counter.fetch_add(1, std::memory_order_relaxed);
    }
}

int main() {
    std::thread t1(task);
    std::thread t2(task);

    t1.join();
    t2.join();

    std::cout << "Final counter value: " << counter << '\n';
    // Output: Final counter value: 2000
}

Embedded Applicability: High

  • Properly aligned integer and pointer types typically map directly to hardware atomic instructions, resulting in zero overhead.
  • is_lock_free() allows us to confirm at runtime if the implementation is truly lock-free, avoiding implicit system calls.
  • Replaces bulky mutexes, making it ideal for lightweight state synchronization between interrupts and the main loop.
  • Excessively large custom structures may fall back to an internal locking implementation, which we must strictly avoid.

Compiler Support

GCCClangMSVC
4.43.119.0

See Also


部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05