Go Mutex: Not Locked Causes Data Race
In this tutorial, you'll learn about Go Mutex: Not Locked Causes Data Race. We cover key concepts, practical examples, and best practices.
Mutex usage -- Protect shared data with sync.Mutex to prevent data races and concurrent map write panics.
The Problem
Concurrent reads and writes to maps cause fatal panics. Without mutex protection, slices, maps, and other shared state produce data races and corrupt data.
Wrong
var counter int
for i := 0; i < 1000; i++ {
go func() { counter++ }() // Data race!
}
Output:
// Data race on counter. Final value unpredictable.
Right
var mu sync.Mutex
var counter int
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
counter++
mu.Unlock()
}()
}
wg.Wait()
fmt.Println(counter) // 1000
Output:
1000
Prevention
- Always Lock before modifying shared state
- Use defer Unlock() when Lock is early in function
- Keep locked sections small (critical section)
- Don't embed mutexes by value (embed *Mutex or pointer)
- Use -race flag to detect data races
Common Mistakes with sync mutex
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro