go runtime_error ai_generated true

panic: sync: mutex is locked

ID: go/mutex-copied-after-use

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

A sync.Mutex or other sync primitive is copied after use, causing the lock state to be duplicated and leading to deadlock or panic when the copy is used.

generic

中文

sync.Mutex 或其他同步原语在使用后被复制,导致锁状态被复制,使用副本时可能导致死锁或恐慌。

Workarounds

  1. 98% success
    type SafeCounter struct {
        mu sync.Mutex
        v  int
    }
    
    func (c *SafeCounter) Inc() {
        c.mu.Lock()
        c.v++
        c.mu.Unlock()
    }
    
    // Always use *SafeCounter, never copy the struct.
  2. 95% success
    type Counter struct {
        mu *sync.Mutex
        v  int
    }
    
    func NewCounter() *Counter {
        return &Counter{mu: &sync.Mutex{}}
    }
    
    func (c *Counter) Inc() {
        c.mu.Lock()
        c.v++
        c.mu.Unlock()
    }

Dead Ends

Common approaches that don't work:

  1. 100% fail

    The panic will recur unpredictably; it's a fundamental design flaw.

  2. 100% fail

    Copying a mutex is illegal; it cannot be safely copied at all.