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%修复率
87%置信度
0证据数
2024-06-06首次发现

版本兼容性

版本状态引入弃用备注
1.14+ active

根因分析

在没有匹配 Lock() 的情况下调用 mu.Unlock(),通常发生在 Lock 被跳过的路径中 defer Unlock,或 Unlock 执行了两次。

English

mu.Unlock() is called without a matching Lock(), often from a deferred Unlock in a path where Lock was skipped or Unlock ran twice.

generic

解决方案

  1. 94% 成功率
    mu.Lock()
    defer mu.Unlock()
    // critical section
  2. 90% 成功率
    func (s *Store) Get(k string) V {
        s.mu.Lock()
        defer s.mu.Unlock()
        return s.m[k]
    }

无效尝试

常见但无效的做法:

  1. 85% 失败

    Swallowing the fatal error hides the logic bug and can leave the mutex in an inconsistent state.

  2. 80% 失败

    TryLock is not a validity check for Unlock and adds races; the double-unlock still occurs.