go runtime_error ai_generated true

恐慌:sync:互斥锁已被锁定

panic: sync: mutex is locked

ID: go/mutex-copied-after-use

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 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.
  2. 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()
    }

无效尝试

常见但无效的做法:

  1. 100% 失败

    The panic will recur unpredictably; it's a fundamental design flaw.

  2. 100% 失败

    Copying a mutex is illegal; it cannot be safely copied at all.