Fetch and add
- C++ course
- Advanced
- Lesson 29/83
- 5 min
Learn atomic arithmetic with fetch_add and fetch_sub.
fetch_add / fetch_sub
fetch_add(n) adds n to the atomic value and returns the previous value. fetch_sub(n) subtracts similarly. Both are indivisible; no other thread can interleave. This makes them ideal for a lock-free counter.
Example: with std::atomic<int> a{10}; int old = a.fetch_add(5); you get old = 10 and a = 15. The shortcut a += 5; gives the same result. At the CPU level this becomes a single LOCK XADD instruction; no mutex is needed.
Atomic arithmetic
std::atomic overloads basic arithmetic operators. a += 5; equals a.fetch_add(5);; a -= 3; equals a.fetch_sub(3);. ++a and a++ also work atomically.
Atomic arithmetic is ideal for updating a shared counter across multiple threads. It is much faster than a mutex; being lock-free means no waiting. It applies only to integer and pointer types though; arithmetic is not supported on types like std::atomic<std::string>.
Practice fetch_add old and new
Create std::atomic<int> a{10};. Add and capture the previous value with int old = a.fetch_add(5);. Write std::cout << old << " " << a.load();.
Starter code
#include <iostream>
#include <atomic>
int main() {
// Create atomic, fetch_add, print old and new
return 0;
}Sample solution
#include <iostream>
#include <atomic>
int main() {
std::atomic<int> a{10};
int old = a.fetch_add(5);
std::cout << old << " " << a.load();
return 0;
}Expected output
10 15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the fetch_add line
std::atomic<int> a{10};
int old = a.____(5);
std::atomic<int> a{10};
int old = a.fetch_add(5);
Explanation: a.fetch_add(5) adds and returns the old value.
2 What does fetch_add return?
- The previous value Correct answer
- The new value
- A bool
- An error code
Explanation: fetch_add returns the value before the addition.
3 Match each expression to its role
| Term | Meaning |
|---|---|
a.fetch_add(5) |
Add, return old value |
a.fetch_sub(3) |
Subtract, return old value |
a += 5 |
Shortcut for fetch_add |
++a |
Atomic increment |