System Design Academy

Saving…

Lesson 3 of 10 in Module 40 of 45 lessons complete

Locks & Mutexes

Module 4, lesson 3Concept12 min

Definition

Mutex

In plain English
A mutex is a lock that only one goroutine can hold at a time, protecting the code between Lock and Unlock.
Think of it like
It is like the key to a single-person changing room.

Why it exists

Two hospitals request the final blood unit. Checking stock separately from withdrawing it can promise that unit twice.

Hold one mutex across the check and change. Every other reader or writer must use that same mutex.

How it works

Lock contention

In plain English
Lock contention is when many goroutines wait for the same lock, slowing everything down.
Think of it like
Like a long queue for one changing room.

Zero value

In plain English
A zero value is the default value a Go variable has before you set it, and a zero sync.Mutex is ready to use.
Think of it like
Like a new notebook that's ready to write in.
After: both hospitals use the same protected inventory.
Go
package main

import (
	"fmt"
	"sync"
)

type Inventory struct {
	mu    sync.Mutex
	units map[string]int
}

func (s *Inventory) Withdraw(kind string) bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.units[kind] == 0 {
		return false
	}
	s.units[kind]--
	return true
}
func main() {
	s := &Inventory{units: map[string]int{"O": 1}}
	var wg sync.WaitGroup
	for i := 0; i < 2; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); fmt.Println(s.Withdraw("O")) }()
	}
	wg.Wait()
}

G1 acquires Mutex while G2 waits, then G1 unlocks and G2 acquires it.

Only one holder enters the protected code.

G1 acquires Mutex while G2 waits, then G1 unlocks and G2 acquires it.

  • Put defer mu.Unlock() immediately after mu.Lock().
  • Keep slow network and disk calls outside the protected section.
  • Use pointer receivers; never copy a mutex after its first use.
  • Run go vet to catch accidental lock copies. Run go test -race to exercise shared accesses.

Unlocking makes earlier protected writes visible to a later holder of the same mutex. Merely sleeping provides no such guarantee.

Examples

Withdraw the final unit

Two hospitals share one inventory. Exactly one withdrawal should succeed.

After: both hospitals use the same protected inventory.
Go
package main

import (
	"fmt"
	"sync"
)

type Inventory struct {
	mu    sync.Mutex
	units map[string]int
}

func (s *Inventory) Withdraw(kind string) bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.units[kind] == 0 {
		return false
	}
	s.units[kind]--
	return true
}
func main() {
	s := &Inventory{units: map[string]int{"O": 1}}
	var wg sync.WaitGroup
	for i := 0; i < 2; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); fmt.Println(s.Withdraw("O")) }()
	}
	wg.Wait()
}

One result is true and one is false. Which hospital succeeds depends on timing.

The insight

A mutex makes check-then-act one protected operation.

Trade-offs

Pros

  • Protect complex shared state.
  • Keep related checks and updates together.

Cons

  • Busy locks create queues.
  • Holding a lock too long delays others.

Use when

  • Several goroutines change one object.
  • Several fields must stay consistent.

Avoid when

  • One goroutine owns the data.
  • No data is shared between tasks.

Quick check

Where should defer mu.Unlock() go?
Why move the SMS call outside the locked section?

Takeaways

  • A mutex admits one holder at a time.
  • Lock, then immediately defer Unlock.
  • Keep critical sections short and free of slow external calls.

Try the quick check above whenever you feel ready.

Previous: Race Conditions & Critical Sections