Locks & Mutexes
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.
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.
- 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.
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.
Borrow three licences
Four readers compete for three licences. Every Borrow call uses the same book lock.
package main
import (
"fmt"
"sync"
)
type Book struct{ licences int }
func (b *Book) Borrow() bool {
if b.licences == 0 {
return false
}
b.licences--
return true
}
func main() {
b := &Book{licences: 3}
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() { defer wg.Done(); fmt.Println(b.Borrow()) }()
}
wg.Wait()
}
package main
import (
"fmt"
"sync"
)
type Book struct {
mu sync.Mutex
licences int
}
func (b *Book) Borrow() bool {
b.mu.Lock()
defer b.mu.Unlock()
if b.licences == 0 {
return false
}
b.licences--
return true
}
func main() {
b := &Book{licences: 3}
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() { defer wg.Done(); fmt.Println(b.Borrow()) }()
}
wg.Wait()
}
Exactly three calls succeed after the fix. Their print order can vary.
The insight
Protect the check and change together.
Send SMS after assignment
Assigning a locker needs shared state. Sending its SMS does not need that state.
package main
import (
"fmt"
"sync"
"time"
)
type Lockers struct {
mu sync.Mutex
next int
}
func (s *Lockers) assign() int {
s.mu.Lock()
defer s.mu.Unlock()
s.next++
time.Sleep(20 * time.Millisecond)
return s.next
}
func main() {
s := &Lockers{}
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
wg.Add(1)
go func() { defer wg.Done(); fmt.Println("SMS", s.assign()) }()
}
wg.Wait()
}
package main
import (
"fmt"
"sync"
"time"
)
type Lockers struct {
mu sync.Mutex
next int
}
func (s *Lockers) assign() int {
s.mu.Lock()
defer s.mu.Unlock()
s.next++
return s.next
}
func main() {
s := &Lockers{}
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
wg.Add(1)
go func() { defer wg.Done(); id := s.assign(); time.Sleep(20 * time.Millisecond); fmt.Println("SMS", id) }()
}
wg.Wait()
}
The helper returns before the SMS starts, so its deferred unlock has already run. SMS delivery order can vary.
The insight
Keep slow work outside the critical section.
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
Takeaways
- A mutex admits one holder at a time.
- Lock, then immediately defer Unlock.
- Keep critical sections short and free of slow external calls.