go runtime_error ai_generated true

警告:数据竞争(协程写操作)

WARNING: DATA RACE (goroutine write)

ID: go/goroutine-race-condition-write

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-09-10首次发现

版本兼容性

版本状态引入弃用备注
1.21 active
1.22 active

根因分析

多个协程并发访问同一变量,且至少有一个写操作,没有同步机制。

English

Multiple goroutines access the same variable concurrently, with at least one write, without synchronization.

generic

解决方案

  1. 98% 成功率 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()
        }()
    }
  2. 95% 成功率 Use atomic operations for simple types
    var counter int64
    for i := 0; i < 10; i++ {
        go func() {
            atomic.AddInt64(&counter, 1)
        }()
    }

无效尝试

常见但无效的做法:

  1. Ignoring the race warning 95% 失败

    Data races lead to undefined behavior, crashes, or corrupted data.

  2. Using time.Sleep to synchronize 90% 失败

    Sleep does not guarantee ordering or atomicity; races persist.