Mutex vs Channel

When to Use Which in Go

Use Mutexes to protect shared variables from concurrent access and Channels to pass data between goroutines without sharing state.

Use a Mutex when multiple goroutines must access and modify the same shared variable safely; use a Channel when you need to pass data between goroutines to avoid shared state entirely. Mutexes protect data in place, while Channels move data to a single owner.

// Mutex: Protect shared state
var mu sync.Mutex
var count int

func increment() {
    mu.Lock()
    count++
    mu.Unlock()
}

// Channel: Pass data between goroutines
func worker(done chan bool) {
    // Process data without shared variables
    done <- true
}