Mutex vs Channels in Golang
Problem Mutex versus channels in Go — when do you use each?
Be ready to discuss
- Mutex:
sync.Mutex/RWMutexprotects shared memory by admitting one goroutine at a time to a critical section — the right tool for guarding a counter, a map, or a cache;RWMutexwhen reads dominate writes. - Channels: Go's "share memory by communicating" philosophy — pass data (and ownership of it) between goroutines instead of guarding it in place.
- Where channels fit best: coordinating control flow — pipelines, worker pools, fan-in/fan-out, signalling completion or cancellation, a buffered channel as a semaphore.
- Where a mutex fits best: simple shared state with no ownership transfer, and hot paths where channel send/receive overhead and scheduler involvement are measurable.
- Buffered versus unbuffered channels, and the failure modes: deadlock on an unbuffered send with no receiver, goroutine leaks when nobody drains a channel, and panic on send to a closed channel.
- Related idioms:
sync.RWMutexversussync/atomicfor simple counters,sync.Once, andcontext.Contextas the standard cancellation channel. - The rule of thumb to state: mutex for protecting state, channels for transferring data and coordinating goroutines — and
go test -raceas the arbiter when unsure.
asked …