go
runtime_error
ai_generated
true
WARNING: DATA RACE
ID: go/goroutine-race-condition
80%Fix Rate
85%Confidence
0Evidence
2024-07-20First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
90% success Use mutex to protect shared variable access
var mu sync.Mutex var counter int mu.Lock() counter++ mu.Unlock()
-
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:
-
Adding time.Sleep to reduce race likelihood
95% fail
Sleep does not synchronize access; race condition still exists and may manifest under different loads
-
Using atomic operations on non-atomic types
80% fail
Atomic package only works on specific types; using it incorrectly can cause data races