Table of Contents

<atomic>

<atomic> provides std::atomic<T> for lock-free shared data between threads. Atomic operations guarantee visibility and ordering without explicit locks, which is critical for low-latency multithreaded code.

Each atomic operation specifies a memory ordering constraint (relaxed, release, acquire, seq_cst) that trades off ordering guarantees for performance. For most code, the default seq_cst is safe; performance-critical paths optimize ordering carefully.

Example

This example shows four threads incrementing a shared atomic counter without using explicit locks, ensuring thread-safe, lock-free access.

// compile: g++ -std=c++11 -pthread -o atomicexample atomicexample.cpp
// run: ./atomicexample
// description: thread-safe counter using atomic
 
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
 
std::atomic<int> counter(0);
 
void increment() {
    for (int i = 0; i < 1000; ++i) {
        counter.fetch_add(1, std::memory_order_relaxed);
    }
}
 
int main() {
    std::vector<std::thread> threads;
    for (int i = 0; i < 4; ++i) {
        threads.emplace_back(increment);
    }
    for (auto& t : threads) t.join();
 
    std::cout << "final counter: " << counter.load() << "\n";
 
    return 0;
}