std::atomic
- C++ course
- Advanced
- Lesson 25/83
- 5 min
Learn atomic operations with std::atomic.
std::atomic
std::atomic<T> holds a shared T value without a data race. All reads and writes are indivisible; only one operation happens at a time. The syntax is std::atomic<int> a{0};.
Atomic is faster than a mutex because it makes no system call; most of the time it runs as a single CPU instruction. load() reads, store(v) writes. Shortcuts like a = 5; and int x = a; also become atomic operations automatically. Atomic is ideal for small shared data such as counters and flags.
load and store
To read an atomic value use a.load(); to write use a.store(v). This explicit form makes the read/write intent clear. The shortcut also works: int x = a; equals x = a.load();; a = 5; equals a.store(5);.
The is_lock_free() member tells whether operations are truly atomic at the hardware level. When it returns true no mutex is used; when false a hidden mutex lies underneath. For most basic types (int, bool, pointer) it returns true; for large structs it may return false.
Practice store and load
Create std::atomic<int> a{0};. Write a value with a.store(5); and read it with std::cout << a.load();. Include the <atomic> header.
Starter code
#include <iostream>
#include <atomic>
int main() {
// Create an atomic, store and load, print
return 0;
}Sample solution
#include <iostream>
#include <atomic>
int main() {
std::atomic<int> a{0};
a.store(5);
std::cout << a.load();
return 0;
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does std::atomic prevent?
- Data races Correct answer
- Memory leaks
- Exceptions
- Thread count
Explanation: std::atomic prevents data races on a shared value.
2 Complete the store line
std::atomic<int> a{0};
____(5);
std::cout << a.load();
std::atomic<int> a{0};
a.store(5);
std::cout << a.load();
Explanation: a.store(5) writes atomically.
3 Match each expression to its role
| Term | Meaning |
|---|---|
a.load() |
Atomic read |
a.store(v) |
Atomic write |
std::atomic<int> |
Atomic int declaration |
a.is_lock_free() |
Is lock-free? |