go runtime_error ai_generated true

fatal error: concurrent slice read and slice write

ID: go/racy-slice-access

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.21 active

Root Cause

Multiple goroutines access the same slice without synchronization, causing data races.

generic

中文

多个 goroutine 在没有同步的情况下访问同一个 slice,导致数据竞态。

Workarounds

  1. 95% success Use a mutex to synchronize all accesses
    var mu sync.Mutex
    mu.Lock()
    slice[i] = value
    mu.Unlock()
  2. 90% success Use atomic operations for simple types
    var val atomic.Value
    val.Store(mySlice)
    // then load and use

Dead Ends

Common approaches that don't work:

  1. Using a channel to pass slice elements 80% fail

    If the underlying slice is still shared, races can occur on the backing array.

  2. Copying the slice before writing 75% fail

    Shallow copy shares the underlying array; deep copy needed.