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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
