Why This Happens
sync.Mutex must not be copied after first use because the copy gets a snapshot of the lock state. If the original is locked, the copy starts in a locked state, leading to deadlocks. Always use a pointer to a mutex.
The Problem
type SafeMap struct {
mu sync.Mutex
m map[string]int
}
func process(sm SafeMap) { // copies the mutex!
sm.mu.Lock()
defer sm.mu.Unlock()
sm.m["key"] = 1
}The Fix
func process(sm *SafeMap) { // pointer, no copy
sm.mu.Lock()
defer sm.mu.Unlock()
sm.m["key"] = 1
}Step-by-Step Fix
- 1
Identify the copy
Find where a struct containing a sync.Mutex is passed by value or assigned to another variable.
- 2
Use a pointer
Change the function parameter or assignment to use a pointer instead of a value.
- 3
Check all call sites
Verify all places that use the struct pass it by pointer.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free