go runtime_error ai_generated true

恐慌:同步:互斥锁已锁定(复制值)

panic: sync: mutex is locked (copied value)

ID: go/mutex-copy-value

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

版本兼容性

版本状态引入弃用备注
1.0 active
1.1 active

根因分析

sync.Mutex(或其他同步原语)在锁定后按值复制。互斥锁不应被复制;复制已锁定的互斥锁会导致未定义行为,并可能引起恐慌。

English

A sync.Mutex (or other sync primitives) is copied by value after being locked. Mutexes should never be copied; copying a locked mutex leads to undefined behavior and can cause panics.

generic

解决方案

  1. 95% 成功率 Use a pointer to the struct that contains the mutex
    type SafeStruct struct {
        mu sync.Mutex
        data int
    }
    func NewSafeStruct() *SafeStruct {
        return &SafeStruct{}
    }
  2. 90% 成功率 Embed the mutex as a pointer field
    type SafeStruct struct {
        mu   *sync.Mutex
        data int
    }
    func NewSafeStruct() *SafeStruct {
        return &SafeStruct{mu: &sync.Mutex{}}
    }

无效尝试

常见但无效的做法:

  1. Using a pointer to the mutex but still copying it 85% 失败

    If the struct containing the mutex is copied, the mutex is still copied even if it's a pointer field; the pointer itself is copied, but the underlying mutex is shared incorrectly.

  2. Ignoring the panic and continuing execution 95% 失败

    The panic is fatal and will crash the program; ignoring it is not possible without recovery, and even then the mutex state is corrupted.