skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
hpp-atomic
This page is read only. You can view the source, but not change it.
# <atomic> **[<atomic>](https://en.cppreference.com/w/cpp/header/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. This example shows four threads incrementing a shared atomic counter without using explicit locks, ensuring thread-safe, lock-free access. ```cpp // 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; } ```
Page Tools
Show pagesource
Backlinks
Back to top