go runtime_error ai_generated true

WARNING: DATA RACE

ID: go/goroutine-race-condition

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active
1.21 active

Root Cause

Multiple goroutines access the same variable concurrently without synchronization, and at least one is a write

generic

中文

多个协程并发访问同一变量且未同步,至少有一个是写操作

Workarounds

  1. 90% success Use mutex to protect shared variable access
    var mu sync.Mutex
    var counter int
    mu.Lock()
    counter++
    mu.Unlock()
  2. 85% success Use channels to communicate instead of sharing memory
    ch := make(chan int)
    go func() {
        ch <- 1
    }()
    val := <-ch

Dead Ends

Common approaches that don't work:

  1. Adding time.Sleep to reduce race likelihood 95% fail

    Sleep does not synchronize access; race condition still exists and may manifest under different loads

  2. Using atomic operations on non-atomic types 80% fail

    Atomic package only works on specific types; using it incorrectly can cause data races