Find a course

Module 3: Synchronization and DeadlockLesson 6 of 1116 min

Race Conditions, Mutexes and Semaphores

Find out why counter++ is not safe with threads, what a critical section needs, and how mutexes, semaphores and atomic instructions protect shared data.

Step 1 of 13Learn

The vanishing ticket sales

A concert ticket site keeps a shared counter of seats sold. Two server threads each handle a purchase at the same instant, and each runs the line sold = sold + 1. The counter started at 100. Afterward it reads 101, not 102. One sale has vanished.

The reason is that one line of code is really three machine steps:

  1. Load the value of sold from memory into a register.
  2. Add 1 to the register.
  3. Store the register back to memory.

Now interleave two threads:

  • Thread 1 loads 100.
  • Thread 2 loads 100.
  • Thread 1 adds 1 and stores 101.
  • Thread 2 adds 1 and stores 101.

Both did their job correctly, yet the result is wrong. This is a race condition: the outcome depends on the exact timing of threads, which the programmer doesn't control. The scheduler can preempt a thread between any two instructions, and on a multicore machine both threads may run truly simultaneously.

Race conditions are some of the nastiest bugs in computing. They may appear once in a million runs, vanish when you add debugging output (which changes the timing), and surface only under heavy load in production. Real accidents, from medical devices to stock exchanges and power grid monitoring, have been traced to them.

Step 2 of 13Practice · Diagram

How one ticket sale vanishes

One possible interleaving of two threads running sold = sold + 1. Tap each step.

Which step makes the lost update inevitable?

Tap the shape that answers the question, then press Check.

How one ticket sale vanishesProcess diagram: T1 loads 100 → T2 loads 100 → T1 stores 101 → T2 stores 101.T1 loads 100T2 loads 100T1 stores 101T2 stores101
T1 loads 100
T2 loads 100

T2 reads before T1 has stored its result.

T1 stores 101
T2 stores 101

Overwrites T1's update with the same value.

Step 3 of 13Practice · Work it out

Two threads each run counter++ exactly once on a shared counter that starts at 5, with no locking. Considering every possible interleaving of their load, add and store steps, what is the smallest final value the counter can have?

Step 4 of 13Learn

Critical sections and what a fix must guarantee

A critical section is a piece of code that accesses shared data and must not be run by more than one thread at a time. In the ticket example, the load-add-store sequence is a critical section.

Any correct solution to the critical-section problem must provide three properties:

  • Mutual exclusion: at most one thread is inside the critical section at any moment.
  • Progress: if no thread is inside and some want to enter, one of them must be allowed in; the decision can't be postponed forever.
  • Bounded waiting: once a thread asks to enter, there is a limit on how many times others can enter before it gets its turn, so no thread starves.

Notice what a naive fix gets wrong. Suppose each thread checks a shared flag: if busy is false, set busy to true and enter. The check and the set are themselves two steps, so two threads can both see false and both enter. You've moved the race, not removed it.

Correct solutions need help from hardware. Processors provide atomic instructions that read and modify a memory location in one indivisible step, such as test-and-set and compare-and-swap (CAS). CAS says: if this location still holds the value I expect, replace it with my new value, and tell me whether it worked. Every lock in a modern OS is built on instructions like these.

Step 5 of 13Practice · Select all that apply

Which properties must a correct solution to the critical-section problem guarantee? Select all that apply.

Select all that apply.

Step 6 of 13Learn

Mutexes and spinlocks

The most common tool is a mutex (mutual exclusion lock). It has two operations:

  • lock() (acquire): if the mutex is free, take it and continue; if another thread holds it, wait.
  • release(): give it up, letting one waiting thread proceed.

The fixed ticket code becomes: lock, sold = sold + 1, release. Only the thread holding the mutex can be between those calls, so updates can no longer interleave.

How a thread waits matters. A spinlock waits by looping, repeatedly trying an atomic instruction until the lock becomes free. That burns CPU time, but if the lock is held for only a few dozen instructions on another core, spinning is faster than going to sleep and being woken up. Kernels use spinlocks for very short critical sections.

A blocking mutex puts the waiting thread to sleep in the kernel and wakes it when the lock is released. No CPU is wasted, but sleeping and waking cost a couple of context switches. Modern implementations, such as Linux futexes, combine the two: try an atomic instruction in user space first, spin briefly, and only ask the kernel to sleep if the lock stays busy.

Locks bring their own costs. Hold a lock too long and threads queue up behind it, wiping out the benefit of multiple cores; this is lock contention. Forget to release the lock, often on an error path, and every other thread waits forever.

Step 7 of 13Compare

Blocking mutex vs. spinlock

AspectBlocking mutexSpinlock
While waitingSleeps; the core runs something elseLoops, trying again and again
CostContext switches to sleep and wakeBurns CPU while it spins
Best whenLocks may be held a long timeLocks are held for a few instructions on multicore
Typical useApplication codeInside kernels, short critical sections

Step 8 of 13Practice · Spot the mistake

This pseudocode transfers money between two accounts that other threads also use. Select the line that makes it unsafe.

Step 9 of 13Learn

Semaphores and the producer-consumer problem

A semaphore, invented by Edsger Dijkstra in the 1960s, is a counter with two atomic operations:

  • wait() (also called P or down): if the count is above zero, decrease it and continue; otherwise sleep until it is.
  • signal() (also called V or up): increase the count and wake a sleeping thread if there is one.

A semaphore that starts at 1 behaves like a mutex. One that starts at N limits how many threads can use a resource at once: a semaphore of 5 could cap simultaneous database connections at 5.

The classic use is the producer-consumer (bounded buffer) problem. Producers put items into a buffer of size N; consumers take them out. Producers must wait when the buffer is full, consumers when it's empty. Three semaphores solve it:

  • empty, starting at N, counts free slots. Producers wait on it before adding.
  • full, starting at 0, counts filled slots. Consumers wait on it before removing.
  • mutex, starting at 1, protects the buffer's internal pointers.

A producer does wait(empty), wait(mutex), add item, signal(mutex), signal(full). A consumer mirrors it. Getting the order wrong, such as waiting on mutex before empty, can freeze everything, as the next lesson explains.

Higher-level languages offer friendlier tools built on the same ideas: condition variables, monitors, Java's synchronized, thread-safe queues, and atomic counter types.

Step 10 of 13Diagram

A bounded buffer with two semaphores

A bounded buffer with two semaphoresCycle diagram: Producer: wait(empty) → Put item (with mutex) → Producer: signal(full) → Consumer: wait(full) → Take item (with mutex) → Consumer: signal(empty).Buffer of N slotsProducer:wait(empty)Put item (withmutex)Producer:signal(full)Consumer:wait(full)Take item (withmutex)Consumer:signal(empty)

Tap a shape with to see more.

Producer: wait(empty)

Sleeps if every slot is full.

Put item (with mutex)
Producer: signal(full)

One more item available.

Consumer: wait(full)

Sleeps if the buffer is empty.

Take item (with mutex)
Consumer: signal(empty)

One more free slot.

Step 11 of 13Practice · Work it out

A print server uses a counting semaphore initialized to 3 to limit simultaneous print jobs. Five threads call wait() on it, one after another, and none has called signal() yet. How many threads are blocked?

Step 12 of 13Note

Step 13 of 13Practice · True or false

Wrapping every shared variable access in the same single global lock guarantees correctness and also keeps full multicore performance.