Chapter 1 · Section 7 of 8 · 2 min read

Pitfalls

Five mistakes that account for most mutex bugs. The outputs below are real, from Go 1.25.2.

1. Forgetting to unlock on one path

func (c *Counter) IncIfSmall(limit int) {
	c.mu.Lock()
	if c.n >= limit {
		return // the lock is never released
	}
	c.n++
	c.mu.Unlock()
}

The early return leaves the mutex locked, and the next goroutine to call Lock waits forever. The fix is defer c.mu.Unlock() on the line after Lock, as Counter does. A deferred call runs on every way out of the function.

2. Unlocking a mutex that is not locked

var mu sync.Mutex
mu.Unlock()
fatal error: sync: unlock of unlocked mutex

This is not a panic you can recover from. It is the fatal("sync: unlock of unlocked mutex") call you saw in unlockSlow. Go treats it as a bug in the program that cannot be handled safely.

3. Copying a mutex

type Stats struct {
	mu sync.Mutex
	n  int
}

func report(s Stats) { // s is a copy, including the mutex
	fmt.Println(s.n)
}

A copy has its own state, so it no longer protects the original. Go does not stop you at compile time, but go vet does:

copy/main.go:13:15: report passes lock by value: pit/copy.Stats contains sync.Mutex
copy/main.go:19:9: call of report copies lock value: pit/copy.Stats contains sync.Mutex

The documentation says "A Mutex must not be copied after first use." Pass pointers (*Stats) and run go vet in your CI.

4. Locking twice in the same goroutine

var mu sync.Mutex

func outer() {
	mu.Lock()
	defer mu.Unlock()
	inner()
}

func inner() {
	mu.Lock() // already held by outer in this goroutine
	defer mu.Unlock()
}

Go's mutex is not reentrant. This program, with no other goroutines, ends with:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [sync.Mutex.Lock]:
internal/sync.runtime_SemacquireMutex(...)
internal/sync.(*Mutex).lockSlow(...)
	.../internal/sync/mutex.go:149 +0x170
...
main.inner()

(Shortened.) Line 149 is the runtime_SemacquireMutex call you read in the Lock section. The runtime could tell that every goroutine was asleep. In a real server other goroutines keep running, so you would not get this message. The goroutine would just wait forever. Chapter 3 covers reentrant locks and how to structure code to avoid the problem.

5. A mutex that guards too little

The mutex protects what you put inside it, and nothing else. Two common ways to guard too little:

  • Check outside, act inside. if a.balance >= amount { a.mu.Lock(); a.balance -= amount; a.mu.Unlock() } has the overdraft bug from the problem section again. The check must be inside the lock.
  • Lock the write but not the read. If Value() read c.n without locking, it would race with Inc. The race detector would report it.

What to do instead: write the invariant in a comment next to the mutex, and read every function that touches the data asking "is the lock held here?"