TRT
Sign in

Advanced · Module 12 · Lesson 2 of 5

std::atomic: Counters and Flags Without Mutexes

Replace lock-guarded increments with indivisible fetch operations, compare throughput against mutexes, and signal state with atomic flags.

Pro — members onlyAbout 10 minutes

By the end you can

  • Rewrite a mutex-guarded counter with atomic fetch_add
  • Compare atomic and mutex cost for contended increments
  • Signal between threads with atomic flags and exchanges

Builds on Data Races: The Bug Locks Prevent.

01 · A question first

Eight threads each add one thousand to a shared total. With a lock the answer is right but the profiler shows sleep and wakeups. With one changed type the answer stays right and the lock vanishes. What hardware primitive removes the critical section?

Make a guess before you read on.

02 · The idea

Members only

Unlock the full lesson

This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.

What's inside

  • Start with the problem
  • How the idea works
  • Why it is correct
  • What it costs
  • Pitfalls and variations
  • Where it is used

03 · Practice

Something wrong with this lesson? Report a problem