go runtime_error ai_generated true

panic: sync: mutex is locked (copied value)

ID: go/mutex-copy-value

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.1 active

Root Cause

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

中文

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

Workarounds

  1. 95% success 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% success Embed the mutex as a pointer field
    type SafeStruct struct {
        mu   *sync.Mutex
        data int
    }
    func NewSafeStruct() *SafeStruct {
        return &SafeStruct{mu: &sync.Mutex{}}
    }

Dead Ends

Common approaches that don't work:

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

    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% fail

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