TRT
Sign in

Expert · Module 25 · Lesson 1 of 5

Data races and locks

Two threads incrementing one counter can both be correct line by line and still lose updates. This lesson defines a data race, shows what a mutex fixes, and prices the lock: fast path, futex slow path, contention, convoying and spinlocks.

Pro — members onlyAbout 13 minutes

By the end you can

  • Recognize a data race from its three conditions: same location, at least one write, no ordering
  • Trace a lost update and show where a mutex changes the outcome
  • Compare a spinlock with a sleep lock and pick one for a critical section

Builds on The call stack is a stack, How a function call works.

01 · A question first

Two threads each add a million to the same counter. The loop ends short of 2,000,000, by a different amount every run, and every line of code is correct. Where did the updates go, and what does one lock promise to do about it?

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

  • Two threads, one counter
  • What a data race is
  • Why your machine hides it
  • What a lock promises
  • What a lock costs
  • Spinlocks and sleep locks
  • When a lock is the right answer
  • Where this shows up

03 · Practice

Something wrong with this lesson? Report a problem