go runtime_error ai_generated true

WARNING: DATA RACE (goroutine read)

ID: go/goroutine-race-condition-read

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-10-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.21 active
1.22 active

Root Cause

A goroutine reads a variable while another goroutine writes to it without synchronization.

generic

中文

一个协程读取变量时,另一个协程在无同步的情况下写入该变量。

Workarounds

  1. 97% success Use sync.RWMutex for read preference
    var mu sync.RWMutex
    var data map[string]int
    read := func(key string) int {
        mu.RLock()
        defer mu.RUnlock()
        return data[key]
    }
    write := func(key string, val int) {
        mu.Lock()
        defer mu.Unlock()
        data[key] = val
    }
  2. 95% success Use channels to communicate instead of shared memory
    ch := make(chan int)
    go func() {
        v := <-ch
        // use v
    }()
    ch <- 42

Dead Ends

Common approaches that don't work:

  1. Using a local copy of the variable 70% fail

    The copy is made before the write, but the race still exists at the read point.

  2. Adding more goroutines to distribute load 85% fail

    More goroutines increase the chance of race conditions.