In Go, when would you reach for a channel versus a sync.Mutex to coordinate goroutines?
technical-conceptual · Mid level · software-engineering
What the interviewer is really asking
Assesses whether the candidate understands Go's concurrency primitives well enough to pick the right one by intent — communication versus protecting shared state — instead of defaulting to channels for everything.
What to say
- State the dividing line the Go team itself gives: use a channel when goroutines need to pass data or ownership between each other (communication, pipelines, producer/consumer); use a sync.Mutex when several goroutines just need safe access to the same in-memory state.
- Be honest about cost: a mutex is essentially an atomic acquire/release, so for protecting a simple counter or map it's cheaper and clearer than routing every access through a channel and a dedicated goroutine.
- Reference the idiom without dogma: 'share memory by communicating' is the Go motto, but the official wiki explicitly says don't over-use channels — reach for a mutex when it fits, and verify correctness with the race detector (`go test -race`).
What to avoid
- Claim channels are always the idiomatic choice and mutexes are a code smell; the Go wiki itself pushes back on that.
- Use a channel plus a manager goroutine just to guard a single shared counter, where a mutex is simpler and faster.
- Forget that both still need the race detector — picking a primitive doesn't prove the code is data-race-free.
Example answers
Strong: In a worker pool I used a channel to hand jobs to workers — that's data flowing between goroutines, exactly what channels are for. But the shared metrics counter those workers updated, I guarded with a sync.Mutex, because routing every increment through a channel would have been slower and noisier. I ran `go test -race` to confirm there were no data races.
Weak: Go's motto is don't communicate by sharing memory, share memory by communicating, so I always use channels and avoid mutexes since they're not really idiomatic.