Chapter 1 · Section 1 of 8 · 2 min read

Taking turns

In Chapter 0 two goroutines lost an update because their steps overlapped. This chapter is about the most common cure: let only one goroutine at a time touch the data.

The bank account

A counter is the smallest example. Here is one that hurts more. An account holds 15. Two withdrawals of 10 arrive at the same moment. The code for a withdrawal reads naturally:

func (a *Account) Withdraw(amount int) error {
	if a.balance < amount {          // 1. check
		return ErrInsufficientFunds
	}
	a.balance -= amount              // 2. act
	return nil
}

Each goroutine does its check, then its change. Overlap them:

MomentGoroutine AGoroutine Bbalance
1checks: 15 >= 10, so go ahead15
2checks: 15 >= 10, so go ahead15
3takes 105
4takes 10-5

Both checks passed because both ran before either change. The account is now overdrawn. Notice that the bug is not a lost update on one variable. It is a decision that became wrong between the check and the act. The check and the act belong together. They must happen as one unit that nobody else can interrupt.

What we need

We need a way to say: this stretch of code must run alone. Only one goroutine at a time may be inside it, and the others must wait outside until it finishes. That stretch of code is called a critical section. The tool that enforces it is a mutex, short for mutual exclusion.

A mutex gives you two operations:

  • Lock. If nobody holds the mutex, you take it and carry on. If somebody does, you wait.
  • Unlock. You give it up, and one of the waiters may take it.

The code between your Lock and your Unlock is the critical section.

What this chapter covers

  • how a mutex fixes the counter and the bank account, and what it costs you in waiting;
  • how Go's sync.Mutex is built, read from the real source of Go 1.25.2;
  • why a mutex needs a policy for who goes next, and what Go does about it;
  • how the Linux kernel, Java, C++, Rust and Python make different choices;
  • the mistakes people make most often.