go runtime_error ai_generated true

致命错误:对未锁定的互斥锁执行解锁操作

fatal error: sync: unlock of unlocked mutex

ID: go/mutex-lock-already-held

其他格式: JSON · Markdown 中文 · English
85%修复率
85%置信度
1证据数
2023-01-15首次发现

版本兼容性

版本状态引入弃用备注
Go 1.18 active
Go 1.19 active
Go 1.20 active
Go 1.21 active
Go 1.22 active

根因分析

在同一个协程中对未锁定的 sync.Mutex 调用 Unlock(),或者对同一个互斥锁重复解锁。

English

Calling Unlock() on a sync.Mutex that was not locked by the same goroutine, or double-unlocking a mutex.

generic

官方文档

https://pkg.go.dev/sync#Mutex

解决方案

  1. 始终在同一个函数中配对 Lock() 和 Unlock(),在 Lock() 后立即使用 defer 以避免不匹配
  2. 使用 sync.Mutex.TryLock()(Go 1.18+)在解锁前检查锁是否被持有,但推荐使用结构化模式

无效尝试

常见但无效的做法:

  1. 75% 失败

    Defer runs even if the lock was never acquired (e.g., due to early return), causing an unlock of an unlocked mutex.

  2. 90% 失败

    The Go runtime checks that the unlocking goroutine is the same one that locked it; cross-goroutine unlocks panic.