Part 1 of 7 · 1 min read
Why this page comes third
In this module you will
- Use the POSIX mutex calls correctly, including
trylockand the error-checking and recursive types. - Explain why a sleeping lock beats a spinlock when waits are long, with measured numbers.
- Describe how a futex gives a mutex a system-call-free fast path.
- Trace the three states of a futex-based mutex through a contended lock and unlock.
- State the rules that make mutex-protected code correct and fast.
Page 2 built locks that wait by spinning, and showed their cost: when the holder is not running, the spinners burn whole time slices. The lock that programs use in practice, the mutex, takes the other path. A waiting thread goes to sleep, and the unlocking thread wakes it. This page shows how that works, and the next pages build on it. The sources are "The Linux Programming Interface" (TLPI), chapter 30, "Operating Systems: Three Easy Pieces" (OSTEP), chapter 28, "Operating System Concepts" (OSC), chapter 6, and the manual pages pthread_mutex_lock(3) and futex(2). All programs were compiled with gcc -O2 -Wall -Wextra -pthread and run on a two-processor Linux machine.
About this example About this example
Real: The C programs, commands and outputs on this page were compiled with gcc -Wall -Wextra -pthread and run on a Linux test machine (2 processors, kernel 6.18, glibc 2.39).
Scripted: The worked traces use small numbers chosen so they can be followed by hand.
Not real: The page simplifies real systems. Actual kernels add more cases, limits and tuning than a short page can show.