When working with goroutines , you often need to share data between them. However, concurrent access to shared variables can lead to race conditions ,where multiple goroutines try to read/write the same variable at the same time, leading to unpredictable behavior.
To solve this, Go provides a synchronization mechanism called Mutex from the sync package.
What is a Mutex?
A mutex (short for mutual exclusion) allows only one goroutine to access a critical section of code at a time.
In Go, it's represented by the sync.Mutex type.
You call Lock() before accessing the shared resource and Unlock() after you're done.
Example with Mutex
package main
import (
"fmt"
"sync"
"time"
)
func main() {
counter := 0
var mu sync.Mutex{} // Create a mutex
var wg sync.WaitGroup // To wait for all goroutines
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock() // Lock the mutex before accessing counter
counter++ // Critical section
mu.Unlock() // Unlock after done
}()
}
wg.Wait() // Wait until all goroutines complete
fmt.Println("Final counter:", counter)
}
Output:
Final counter: 1000
🚀 Tips
Always use defer mu.Unlock() to ensure unlocking even if there’s a panic or early return.
Avoid holding locks for too long to prevent performance issues.
Use the -race flag when running your program to detect race conditions:
go run -race main.go
Top comments (2)
Very nicely explained.....
Thank you...
Would be complete if discussed about -race while running the program
Thanks Sreekar.
I was away.
Yes, when running a Go program with the -race flag, it is enabling race detection.