C++: lock-free counting with std::atomic

An atomic operation completes as one indivisible step, so no other thread can observe it half done. std::atomic<int> provides atomic reads, writes, and read-modify-write operations such as fetch_add. Unlike a plain int, concurrent access to an atomic is not a data race.

C++
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

int main() {
  std::atomic<int> counter{0};
  std::vector<std::thread> threads;

  for (int t = 0; t < 4; ++t) {
    threads.emplace_back([&counter] {
      for (int i = 0; i < 50000; ++i) {
        counter.fetch_add(1, std::memory_order_relaxed);
      }
    });
  }
  for (std::thread& th : threads) {
    th.join();
  }
  std::cout << "counter=" << counter.load() << "\n";
}
Read the full lesson