A basic example using fetch_add would look like this:
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<long long> count;
void worker() {
count.fetch_add(1, std::memory_order_relaxed);
}
int main() {
std::thread t1(worker);
std::thread t2(worker);
std::thread t3(worker);
std::thread t4(worker);
std::thread t5(worker);
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
std::cout << "Count value:" << count << 'n';
}
The result of this example code would be 5. As we can see here, we can implement a basic counter this way with atomics, instead of having to use any mutexes or similar in order to provide thread synchronization.