06 / 10

When should you use sync.Mutex vs channels for shared state?

Use mutexes to protect shared data structures accessed by multiple goroutines. Use channels to communicate data or signal events between goroutines. Do not mix both patterns on the same resource.

Mutex use cases
  1. 1

    Protecting a shared cache, counter, or map from concurrent reads and writes

  2. 2

    RWMutex when reads dominate: many concurrent readers, rare writers

  3. 3

    Guarding a struct's internal state in a concurrent-safe type

  4. 4

    Short critical sections where channel overhead would be wasteful

Channel use cases
  1. 1

    Passing ownership of data between goroutines — only one goroutine holds the data at a time

  2. 2

    Signaling events: task completion, shutdown, rate limiting tokens

  3. 3

    Pipeline and fan-out patterns where data flows through stages

  4. 4

    Worker pool coordination: jobs channel distributes work, results channel collects output

Mutex for shared state example