go runtime_error ai_generated true

fatal error: sync: 解锁未锁定的互斥锁

fatal error: sync: unlock of unlocked mutex

ID: go/mutex-unlock-of-unlocked

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-06-18首次发现

版本兼容性

版本状态引入弃用备注
1.x active — — —

根因分析

对当前未由本 goroutine 锁定的 sync.Mutex 调用 Unlock()。常由重复 Unlock 引起,或 defer 中的 Unlock 在提前返回路径已解锁后再次执行。

English

Unlock() is called on a sync.Mutex that is not currently locked by this goroutine. Often caused by double Unlock, or Unlock in a defer that runs after an early return path already unlocked.

generic

解决方案

  1. 95% 成功率
    Use defer mu.Unlock() immediately after a single mu.Lock() and never unlock elsewhere:
    mu.Lock()
    defer mu.Unlock()
    // critical section
  2. 85% 成功率
    Encapsulate lock/unlock in a helper that tracks state, or restructure so the lock scope matches the function scope exactly.

无效尝试

常见但无效的做法:

  1. 95% 失败

    This is a fatal runtime error, not a recoverable panic; recover does not catch it.

  2. 70% 失败

    Increases risk of forgetting to unlock on error paths, causing deadlocks instead.