Summary - Atomic
- C++ course
- Advanced
- Lesson 30/83
- 5 min
Combine atomic, memory_order and compare_exchange to write a counter.
Summary - Atomic
In this group you met five tools of atomic operations: shared values with std::atomic, ordering guarantees with memory_order, CAS with compare_exchange_strong, spinlocks with atomic_flag and atomic arithmetic with fetch_add. They all live in the <atomic> header.
Together these tools let you write lock-free, data-race-free parallel code. Now you will write a small task that combines what you learned: two atomic additions with fetch_add and a print of the result.
Practice Summary: two fetch_add
Create std::atomic<int> a{0};. Do two atomic additions with a.fetch_add(7); and a.fetch_add(3);. Print the result with std::cout << a.load();. Include the <atomic> header.
Starter code
#include <iostream>
#include <atomic>
int main() {
// Create atomic, two fetch_add, print
return 0;
}Sample solution
#include <iostream>
#include <atomic>
int main() {
std::atomic<int> a{0};
a.fetch_add(7);
a.fetch_add(3);
std::cout << a.load();
return 0;
}Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool is the simplest atomic type?
- std::atomic<int>
- std::atomic_flag Correct answer
- std::future
- std::mutex
Explanation: std::atomic_flag is the simplest atomic type; it has only two states.
2 Match each tool to its purpose
| Term | Meaning |
|---|---|
std::atomic<int> |
Shared counter |
memory_order_relaxed |
Weak ordering |
compare_exchange_strong |
CAS swap |
fetch_add |
Atomic addition |
3 Complete the fetch_add line
std::atomic<int> a{0};
a.____(7);
a.fetch_add(3);
std::cout << a.load();
std::atomic<int> a{0};
a.fetch_add(7);
a.fetch_add(3);
std::cout << a.load();
Explanation: a.fetch_add(7) atomically adds 7.