Golang / GoLang Concurrency Mastery Interview Questions
What causes deadlocks in Go and how do you detect and prevent them?
A deadlock occurs when every goroutine is blocked waiting for a resource held by another — a circular dependency from which no goroutine can proceed. The Go runtime detects simple all-goroutine deadlocks and panics with 'all goroutines are asleep — deadlock!'.
// DEADLOCK 1: circular channel wait
ch1 := make(chan int)
ch2 := make(chan int)
go func() { v := <-ch1; ch2 <- v }() // waits for ch1, then sends ch2
go func() { v := <-ch2; ch1 <- v }() // waits for ch2, then sends ch1
// ALL goroutines blocked → runtime: 'all goroutines are asleep'
// DEADLOCK 2: non-reentrant mutex locked twice
var mu sync.Mutex
mu.Lock()
mu.Lock() // DEADLOCK — tries to acquire a lock already held
// DEADLOCK 3: inconsistent lock-acquisition order
var muA, muB sync.Mutex
// goroutine 1: muA.Lock() then muB.Lock() (A→B order)
// goroutine 2: muB.Lock() then muA.Lock() (B→A order) → DEADLOCK
// FIX for #3: enforce a global consistent ordering — always A before B
// DEADLOCK 4: unbuffered send with no receiver
// ch := make(chan int)
// ch <- 1 // blocks forever
// Detection tools:
// 1. Go runtime: 'all goroutines are asleep'
// 2. CTRL+\ sends SIGQUIT → dumps all goroutine stacks
// 3. pprof goroutine endpoint: /debug/pprof/goroutine?debug=2
// 4. context.WithTimeout prevents indefinite blockingPrevention rules: (1) acquire locks in a globally consistent order. (2) Prefer context.Context with deadlines over raw channel waits. (3) Use select with default or a timeout to avoid indefinite blocking. (4) Keep critical sections short and never hold a lock while performing I/O.
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...
