When is it better to use Mutex, and when Channel?
sobes.tech AI
Answer from AI
Mutex and Channel in Go serve different synchronization purposes:
-
Mutex — used to protect access to shared data to prevent race conditions. It locks a critical section, allowing only one goroutine to work with the resource at a time.
-
Channel — used for communication between goroutines, data transfer, and synchronization through message exchange.
When to use:
-
Mutex — if you just need to protect a shared variable or data structure from concurrent access.
-
Channel — if you need to organize data transfer, events, or signals between goroutines, especially when order or asynchrony is important.
Example with Mutex:
var mu sync.Mutex
var counter int
mu.Lock()
counter++
mu.Unlock()
Example with Channel:
ch := make(chan int)
go func() {
ch <- 42 // send
}()
val := <-ch // receive
In summary: Mutex — for data protection, Channel — for communication and synchronization via messages.