Lesson 40 of 45
C++Lesson 40: Atomic Operations (std::atomic)
10 min
Course progress89%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 40 of 45
C++10 min
Keep these ideas in mind as you work through the lesson.
std::atomic)std::atomic provides lock‑free primitives for safe concurrent access to simple data types. They guarantee atomic read‑modify‑write operations and avoid the overhead of mutexes for fine‑grained synchronization.
#include <atomic>
#include <thread>
std::atomic<int> atomicCounter{0};
void inc(int n) {
for (int i = 0; i < n; ++i) {
atomicCounter.fetch_add(1, std::memory_order_relaxed);
}
}
int main() {
std::thread t1(inc, 1000);
std::thread t2(inc, 1000);
t1.join();
t2.join();
std::cout << \"Atomic counter: \" << atomicCounter.load() << '\
';
return 0;
}
std::atomic<int> flag{0};
int expected = 0;
if (flag.compare_exchange_strong(expected, 1)) {
// We successfully set flag from 0 to 1
std::cout << \"Acquired flag\
\";
}
Tip: Use
std::atomic_flagfor a simple spin‑lock, but be wary of busy‑waiting.
<Alert type="warning">Atomic operations are only safe for trivially copyable types. For complex structures, protect them with mutexes or design lock‑free data structures.