Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Go: when should I use a channel instead of a mutex?

clock icon

asked 1 month ago

message icon

2

eye icon

750

"Share memory by communicating" gets quoted constantly, but plenty of real Go code uses sync.Mutex. Is there a practical rule for choosing?

2 Answers

The distinction that holds up in practice: channels pass ownership, mutexes protect state.

Use a mutex when goroutines share a data structure and each just needs exclusive access briefly — a cache, a counter, a connection pool. A channel there adds a goroutine and a hop for no benefit.

1type Cache struct {
2 mu sync.RWMutex
3 m map[string]string
4}
1type Cache struct {
2 mu sync.RWMutex
3 m map[string]string
4}

Use a channel when a value moves from one goroutine to another — a work queue, a pipeline stage, a cancellation signal. The channel is the handoff, and after it the sender must not touch the value.

If you find yourself using a channel of size one as a lock, you wanted a mutex.

Also worth knowing sync.RWMutex is not automatically faster for read-heavy loads — under high core counts the read lock's cache-line contention can lose to a plain Mutex. Benchmark before assuming.

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions