Chapter 1 · Section 8 of 8 · 2 min read
Check yourself
Questions
- What is a critical section, and what is a mutex's job with respect to it?
Answer
A critical section is a piece of code that must run alone. A mutex makes sure only one goroutine at a time is between its Lock and its Unlock.
- In the bank account example, why is it not enough to lock only the line <code>a.balance -= amount</code>?
Answer
The check (a.balance < amount) and the change are one decision. If the check is outside the lock, two goroutines can both pass it before either subtracts, and the balance goes negative.
- Where does the real Go mutex algorithm live in Go 1.25.2, and what does <code>sync.Mutex</code> do?
Answer
In src/internal/sync/mutex.go. sync.Mutex in src/sync/mutex.go wraps an internal/sync.Mutex and forwards each call to it.
- What does the 1 ms threshold control?
Answer
A waiter that fails to acquire the mutex for more than 1 ms switches it to starvation mode, where Unlock hands ownership directly to the first waiter and new arrivals queue at the back.
- Name one thing a Go mutex allows that a Linux kernel mutex does not.
Answer
Unlocking from a different goroutine than the one that locked it. The Go documentation allows it; the kernel documentation says "Only the owner can unlock the mutex."
- Why is <code>defer mu.Unlock()</code> placed right after <code>mu.Lock()</code>?
Answer
It runs on every exit from the function, including early returns and panics, so the lock cannot be left held.
Exercises
- In the contention simulator, find a seed where the mode badge flips to starvation and back to normal more than once. What do the goroutines in the queue have in common at that moment?
- Add a method
Transfer(from, to *Account, amount int) errorto the code package. Which mutex or mutexes does it need to hold? Write it, write a test, and run it under-race. (You will meet the problem it can cause in a later chapter.) - Remove the
deferinCounter.Incand unlock manually at the end. Add an early return for a condition of your choosing and write a test that finds the stuck lock. - Read lines 202-234 of
src/internal/sync/mutex.goin your own Go installation. If your Go version differs from 1.25.2, what changed?
What comes next
A mutex treats every goroutine alike. But many programs read far more often than they write, and readers do not need to exclude one another. Chapter 2 introduces the read-write mutex, which lets any number of readers in together while a writer gets the data alone.