The previous article introduced race conditions, atomicity, and critical sections. The natural response to a race condition is to protect critical sections with a lock: only one goroutine may enter at a time. Locks bring problems of their own. With the wrong locking strategy, your program can freeze (deadlock), spin forever (livelock), or leave one goroutine without any progress while the rest carry on (starvation).
Deadlocks
A deadlock occurs when two or more goroutines are each waiting for a resource held by another, and none of them can proceed. The program does not crash or return an error; it just stops making progress.
The classic scenario involves two locks and two goroutines acquiring them in opposite order:
package mainimport ( "fmt" "sync" "time")func main() { var muA, muB sync.Mutex var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() muA.Lock() fmt.Println("G1: acquired A, waiting for B...") // let both goroutines reach this point time.Sleep(10 * time.Millisecond) muB.Lock() // blocks here: G2 holds B fmt.Println("G1: acquired B") // never printed muB.Unlock() muA.Unlock() }() go func() { defer wg.Done() muB.Lock() fmt.Println("G2: acquired B, waiting for A...") time.Sleep(10 * time.Millisecond) muA.Lock() // deadlock: G1 holds A fmt.Println("G2: acquired A") // never printed muA.Unlock() muB.Unlock() }() wg.Wait() // main blocks here too — all goroutines are asleep}Go's runtime detects when every goroutine in the program is blocked simultaneously and panics:
G1: acquired A, waiting for B...
G2: acquired B, waiting for A...
fatal error: all goroutines are asleep - deadlock!
The Coffman conditions
E. G. Coffman Jr. identified four conditions that must all be present simultaneously for a deadlock to occur. Looking at the example above, all four are satisfied:
1. Mutual exclusion: at least one resource can be held by only one process at a time. Providing mutual exclusion is the whole purpose of sync.Mutex.
2. Hold and wait: a process holds at least one resource while waiting to acquire another. G1 holds muA while waiting for muB. G2 holds muB while waiting for muA.
3. No preemption: a resource can only be released voluntarily by the process holding it. The Go runtime cannot forcibly take muA from G1 and hand it to G2.
4. Circular wait: there is a cycle of processes, each waiting for a resource held by the next. G1 waits for muB (held by G2) → G2 waits for muA (held by G1) → cycle.
Preventing deadlocks
The most practical strategy is to eliminate at least one Coffman condition. Two approaches cover the most common cases.
Consistent lock ordering
Circular wait requires goroutines to acquire locks in different orders. If every goroutine always acquires muA before muB, the cycle is impossible: no goroutine can hold muB while waiting for muA.
// Both goroutines acquire locks in the same order: A → Bgo func() { muA.Lock() muB.Lock() // work with both resources muB.Unlock() muA.Unlock()}()go func() { muA.Lock() // same order — circular wait is impossible muB.Lock() // work with both resources muB.Unlock() muA.Unlock()}()Consistent lock ordering is the simplest and most reliable strategy. In large codebases, enforce it with documentation, code review, or static analysis tooling.
Eliminating hold-and-wait with TryLock
Since Go 1.18, sync.Mutex provides a TryLock() method that attempts to acquire the lock without blocking. If it fails, the goroutine can release everything it already holds and retry later, which breaks the hold-and-wait condition.
go func() { muA.Lock() if !muB.TryLock() { muA.Unlock() // release what we hold instead of waiting // retry later or return an error return } // work with both resources muB.Unlock() muA.Unlock()}()Livelocks
A livelock looks like a deadlock from the outside, since no progress is made, but the goroutines are not blocked. They keep running and changing state without ever completing their work.
The classic analogy is two people walking toward each other in a narrow corridor. Each steps aside to let the other pass, both pick the same side at the same time, and they keep mirroring each other indefinitely without either one getting past.
In code, this emerges when goroutines use TryLock with a fixed retry delay:
package mainimport ( "fmt" "sync" "time")func work(id string, first, second *sync.Mutex, wg *sync.WaitGroup) { defer wg.Done() for attempt := 0; attempt < 10; attempt++ { first.Lock() if second.TryLock() { fmt.Printf("%s: acquired both locks\n", id) second.Unlock() first.Unlock() return } // step aside politely — but both wait the same fixed time first.Unlock() time.Sleep(10 * time.Millisecond) } fmt.Printf("%s: gave up after too many retries\n", id)}func main() { var muA, muB sync.Mutex var wg sync.WaitGroup wg.Add(2) go work("G1", &muA, &muB, &wg) go work("G2", &muB, &muA, &wg) wg.Wait()}Both goroutines start at nearly the same time, acquire their first lock simultaneously, fail on the second, release, and sleep for exactly 10ms. They wake up in sync and repeat the same sequence, so both keep executing code without making progress.
Go's runtime does not detect livelocks. The program runs until the attempt limit (or forever if there is none), burning CPU without producing results, which makes livelocks harder to diagnose than deadlocks.
Preventing livelocks
The fix is to break the synchronization between goroutines. When both retry after the exact same delay, they keep colliding. Adding randomness (jitter) to the retry delay pulls their timing apart: sooner or later one goroutine retries while the other is still sleeping, and it acquires both locks.
import ( "math/rand" "time")func jitteredBackoff(attempt int) time.Duration { // exponential: 1ms, 2ms, 4ms, 8ms... base := time.Duration(1<<attempt) * time.Millisecond jitter := time.Duration(rand.Intn(10)) * time.Millisecond return base + jitter}Replacing the fixed time.Sleep(10 * time.Millisecond) with time.Sleep(jitteredBackoff(attempt)) breaks the lock-step. One goroutine eventually wins, and the exponential base reduces contention pressure over time.
Starvation
Starvation occurs when a goroutine is perpetually unable to acquire a resource because other goroutines keep claiming it first. The starved goroutine makes no progress while the rest of the program keeps running normally, so unlike a deadlock, nothing freezes.
Starvation typically emerges from unfairness: a goroutine that holds a lock, releases it, and immediately re-acquires it before waiting goroutines have a chance to run.
The example below has two goroutines fighting over one sync.Mutex. To keep the explanation short, we'll call the one that keeps taking the lock the greedy goroutine and the one left waiting the starved goroutine. The names are only labels for this example.
package mainimport ( "fmt" "sync" "time")func main() { var mu sync.Mutex var wg sync.WaitGroup // greedy goroutine: holds the lock 50ms, then takes it back wg.Add(1) go func() { defer wg.Done() for i := 0; i < 5; i++ { mu.Lock() time.Sleep(50 * time.Millisecond) // holds for 50ms mu.Unlock() } }() // starved goroutine: asks for the lock while it is held wg.Add(1) go func() { defer wg.Done() time.Sleep(10 * time.Millisecond) // arrive second start := time.Now() mu.Lock() waited := time.Since(start) fmt.Printf("acquired the lock after waiting %v\n", waited) mu.Unlock() }() wg.Wait()}If the greedy goroutine won every round, the starved goroutine would wait the full five cycles, about 250ms. Running the program prints a wait of about 90ms instead. On the first Unlock, the waiting goroutine wakes up but has to compete for the lock, and the greedy goroutine wins because it is already running and calls Lock again right away. By then the starved goroutine has waited more than 1ms, so sync.Mutex switches to starvation mode: the next Unlock hands the lock directly to the goroutine at the front of the queue, and goroutines that arrive later don't try to take it. Go's mutex has worked this way since Go 1.9, so with sync.Mutex the wait is bounded, even though it isn't first come, first served.
Starvation is not exclusive to concurrent programming. An OS scheduler that always favors high-priority processes starves low-priority ones. A database that always serves short transactions first starves long-running queries. In every case, a resource keeps getting taken before the party waiting for it has a chance.
Preventing starvation
sync.RWMutex for read-heavy workloads
When most goroutines only need to read shared data, sync.Mutex is stricter than it needs to be: it blocks all readers even though concurrent reads are safe. sync.RWMutex allows any number of concurrent readers while still giving writers exclusive access. In read-heavy workloads that cuts contention a lot, and with it the chances of starvation.
var mu sync.RWMutex// multiple goroutines can hold RLock simultaneouslymu.RLock()value := sharedDatamu.RUnlock()// Lock blocks all other readers and writersmu.Lock()sharedData = newValuemu.Unlock()Aging
Aging is a scheduling technique that gradually increases the effective priority of a waiting goroutine the longer it has waited. Once its priority rises high enough, it gets scheduled ahead of newcomers. Go's standard library does not provide aging out of the box, but it can be implemented with a priority queue and a dedicated scheduling goroutine.
Fair queuing
For explicit fairness, replace unstructured mutex competition with an ordered queue. Goroutines waiting for a resource join a FIFO channel; the resource is granted in arrival order, making indefinite starvation impossible.
// a simple fair semaphore: requests are served in arrival ordertype FairLock struct { queue chan chan struct{}}A full implementation needs more scaffolding, but the idea stays the same: goroutines are served in the order they arrived.
Summary
| Deadlock | Livelock | Starvation | |
|---|---|---|---|
| Goroutines blocked? | All | None (active but looping) | Some |
| Progress made? | None | None | Partial |
| Go runtime detects? | Yes, it panics | No | No |
| Primary cause | Circular lock dependency | Synchronized retries | Unequal resource access |
| Prevention | Consistent lock ordering | Jitter in retry delay | RWMutex, fair queuing, aging |
All three come from protecting shared resources while several goroutines try to make progress. Deadlocks are the easiest to spot and reason about, because the program halts or panics. With a livelock or starvation the program keeps running, but some of its work never gets done.