Chapter 1 · Section 8 of 8 · 2 min read

Check yourself

Questions

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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."

  1. 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

  1. 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?
  2. Add a method Transfer(from, to *Account, amount int) error to 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.)
  3. Remove the defer in Counter.Inc and unlock manually at the end. Add an early return for a condition of your choosing and write a test that finds the stuck lock.
  4. Read lines 202-234 of src/internal/sync/mutex.go in 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.