std::atomic — thread-safe operations on a single variable without locks.
1#include <atomic>2#include <thread>34std::atomic<int> counter{0};56void increment() {7 for (int i = 0; i < 1000; i++) {8 counter.fetch_add(1, std::memory_order_relaxed);9 }10}1112int main() {13 std::thread t1(increment);14 std::thread t2(increment);15 t1.join(); t2.join();16 std::cout << counter; // 200017}1819// Memory ordering20std::atomic<int> flag{0};2122// Producer23flag.store(1, std::memory_order_release);2425// Consumer26if (flag.load(std::memory_order_acquire) == 1) {27 // Data guaranteed visible28}2930// CAS loop31int expected = 0;32flag.compare_exchange_strong(expected, 1);
Use when: