go
runtime_error
ai_generated
true
恐慌:sync:互斥锁已被锁定
panic: sync: mutex is locked
ID: go/mutex-copied-after-use
80%修复率
82%置信度
0证据数
2024-01-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
sync.Mutex 或其他同步原语在使用后被复制,导致锁状态被复制,使用副本时可能导致死锁或恐慌。
English
A sync.Mutex or other sync primitive is copied after use, causing the lock state to be duplicated and leading to deadlock or panic when the copy is used.
解决方案
-
98% 成功率
type SafeCounter struct { mu sync.Mutex v int } func (c *SafeCounter) Inc() { c.mu.Lock() c.v++ c.mu.Unlock() } // Always use *SafeCounter, never copy the struct. -
95% 成功率
type Counter struct { mu *sync.Mutex v int } func NewCounter() *Counter { return &Counter{mu: &sync.Mutex{}} } func (c *Counter) Inc() { c.mu.Lock() c.v++ c.mu.Unlock() }
无效尝试
常见但无效的做法:
-
100% 失败
The panic will recur unpredictably; it's a fundamental design flaw.
-
100% 失败
Copying a mutex is illegal; it cannot be safely copied at all.