go
runtime_error
ai_generated
true
WARNING: DATA RACE (goroutine write)
ID: go/goroutine-race-condition-write
80%Fix Rate
88%Confidence
0Evidence
2024-09-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
Root Cause
Multiple goroutines access the same variable concurrently, with at least one write, without synchronization.
generic中文
多个协程并发访问同一变量,且至少有一个写操作,没有同步机制。
Workarounds
-
98% success Use sync.Mutex to protect shared variable
var mu sync.Mutex var counter int for i := 0; i < 10; i++ { go func() { mu.Lock() counter++ mu.Unlock() }() } -
95% success Use atomic operations for simple types
var counter int64 for i := 0; i < 10; i++ { go func() { atomic.AddInt64(&counter, 1) }() }
Dead Ends
Common approaches that don't work:
-
Ignoring the race warning
95% fail
Data races lead to undefined behavior, crashes, or corrupted data.
-
Using time.Sleep to synchronize
90% fail
Sleep does not guarantee ordering or atomicity; races persist.