# Mutex Misuse - ID: go-mutex-misuse - Severity: HIGH - CWE: CWE-667 (CWE-667) - Languages: Go ## Description Improper use of sync.Mutex or sync.RWMutex can cause deadlocks, data races, or performance issues. Common issues include missing Unlock, defer in loops, and copying mutex values. ## Detection Message Improper mutex usage can cause: - Deadlocks (Lock without Unlock, recursive locking) - Race conditions (copying mutex breaks its internal state) - Performance issues (defer in loop holds lock too long) ## Remediation 1. Always use defer to unlock: ```go mu.Lock() defer mu.Unlock() // critical section ``` 2. In loops, unlock manually or extract to separate function: ```go // Option 1: Manual unlock for _, item := range items { mu.Lock() process(item) mu.Unlock() } // Option 2: Extract to function for _, item := range items { processLocked(item) // defer works here } ``` 3. Always use pointer receivers for methods that lock: ```go func (s *Server) Handle() { // *Server, not Server s.mu.Lock() defer s.mu.Unlock() } ``` 4. Never call another locking method while holding lock: ```go // BAD func (s *Server) A() { s.mu.Lock() s.B() // Deadlock if B() also locks s.mu.Unlock() } // GOOD - use internal unlocked version func (s *Server) A() { s.mu.Lock() defer s.mu.Unlock() s.bLocked() } func (s *Server) bLocked() { /* no lock here */ } ``` ## Documentation [object Object]