go runtime_error ai_generated true

panic: sync: unlock of unlocked mutex

ID: go/mutex-unlock-before-lock

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-05-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.22 active

Root Cause

Calling Unlock() on a mutex that is not currently locked, often due to logic errors or double unlocking.

generic

中文

在互斥锁未锁定的情况下调用Unlock(),通常由于逻辑错误或重复解锁导致。

Workarounds

  1. 95% success
    Always lock before unlocking. Use defer mutex.Unlock() immediately after locking to ensure proper pairing.
  2. 90% success
    Use sync.RWMutex and ensure Lock/Unlock are in the same goroutine scope to avoid mismatched calls.

Dead Ends

Common approaches that don't work:

  1. 100% fail

    The panic will crash the program; ignoring it is not possible.

  2. 80% fail

    Manual tracking is error-prone and can still race; it does not solve the root cause.

  3. 60% fail

    If the lock is not acquired, defer will still call Unlock and cause the same panic.