Golang / GoLang Concurrency Mastery Interview Questions
What is a livelock and how does it differ from a deadlock in Go programs?
A deadlock: all goroutines are blocked — no progress is possible. A livelock: all goroutines are actively running but constantly reacting to each other in a loop that prevents any meaningful progress — like two people in a corridor who keep stepping in the same direction to let the other pass.
// DEADLOCK: goroutines blocked â Go runtime detects it ch := make(chan int) ch <- 1 // send blocks, no receiver â runtime: 'all goroutines asleep' // LIVELOCK: goroutines running but making no net progress type lock struct{ taken bool } func acquirePolite(own, other *lock) { for { own.taken = true time.Sleep(time.Millisecond) if other.taken { // the other goroutine also has its lock own.taken = false // politely give up and retry â infinite loop! time.Sleep(time.Millisecond) continue } other.taken = true break // rarely reached } } a, b := &lock{}, &lock{} go acquirePolite(a, b) // both goroutines busy but stuck go acquirePolite(b, a) // Go runtime does NOT detect livelocks â goroutines are 'running' // Detection: // - CPU at 100% with no observable progress // - pprof CPU profile shows same functions in an infinite spin // - go tool trace shows goroutines executing but state never advancing // Prevention: // - Randomised exponential backoff: rand.Sleep between retries // - Consistent lock-acquisition ordering // - Prefer context-based timeouts over spin-wait patterns
More Related questions...