ZZomato·Tech KnowledgeL3System Design

Mutex vs Channels in Golang

Problem Mutex versus channels in Go — when do you use each?

Be ready to discuss

  • Mutex: sync.Mutex/RWMutex protects 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; RWMutex when 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.RWMutex versus sync/atomic for simple counters, sync.Once, and context.Context as the standard cancellation channel.
  • The rule of thumb to state: mutex for protecting state, channels for transferring data and coordinating goroutines — and go test -race as the arbiter when unsure.
asked …
LeaderboardSalaryAccount