go runtime_error ai_generated true

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

fatal error: sync: unlock of unlocked mutex

ID: go/unlock-of-unlocked-mutex

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

版本兼容性

版本状态引入弃用备注
1.16 active
1.21 active

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 98% 失败

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

  2. 85% 失败

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