1 of 4

Your RightSignal

Operating systems · 6 of 91 / 3

Locks and mutexes

The concept

Why two threads adding 1 to the same counter can lose a count

Adding 1 to a shared counter is really three CPU steps: load the value, add 1, store it back. If two threads interleave those steps, one update can vanish. This is a race condition: the result depends on timing.

Say the counter is 5. Thread A loads 5, then thread B loads 5 too, each adds 1, and both store 6. Two increments ran but the counter only went up by one.

A mutex (mutual exclusion lock) can be held by only one thread at a time. A thread calls lock() before touching the counter and unlock() after; others calling lock() wait. The code in between is the critical section.