go runtime_error ai_generated true

fatal error: sync: unlock of unlocked mutex

ID: go/unlock-of-unlocked-mutex

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-03-28First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.16 active
1.21 active

Root Cause

sync.Mutex.Unlock() is called on a mutex that is not currently locked by this goroutine, due to double-unlock, unlock without lock, or copying a mutex value.

generic

中文

对当前未被本 goroutine 锁定的互斥锁调用了 Unlock(),原因是重复解锁、未加锁就解锁,或复制了互斥锁值。

Workarounds

  1. 96% success
    mu.Lock()
    defer mu.Unlock()
    // critical section
  2. 94% success
    type Counter struct {
        mu sync.Mutex
        n  int
    }
    func inc(c *Counter) { c.mu.Lock(); defer c.mu.Unlock(); c.n++ }

Dead Ends

Common approaches that don't work:

  1. 98% fail

    This is a fatal runtime error, not a recoverable panic; the process aborts regardless.

  2. 85% fail

    This breaks the critical section semantics and can deadlock if the same goroutine already holds the lock.