What a mutex guarantees
A mutex lets only one thread hold it at a time. Code between lock and unlock runs as a critical section that no other holder can enter until the owner releases.
The atomic core
At the heart sits a single shared word that means locked or unlocked.
- lock uses an atomic operation like compare and swap to flip the word from free to held in one indivisible step.
- If the swap succeeds the caller owns the lock.
- If it fails another thread already holds it, so the caller must wait.
The atomic step matters because two threads might read free at the same instant. The hardware guarantees only one swap wins.
Waiting without burning the core
A naive mutex spins in a loop retrying the swap, which wastes cycles. A real mutex asks the operating system to park the waiting thread, then wakes it when the owner unlocks.
Key idea
A mutex is an atomic flag plus a waiting strategy: one indivisible swap decides the single owner, and parking lets losers sleep instead of spinning.