go runtime_error ai_generated true

警告:数据竞争:协程X写入,协程Y读取(通道发送/接收)

WARNING: DATA RACE: Write by goroutine X, Read by goroutine Y (channel send/recv)

ID: go/goroutine-racy-channel-send-recv

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2026-06-30首次发现

版本兼容性

版本状态引入弃用备注
1.0 active
1.20 active

根因分析

通过通道发送结构体指针,然后发送者在接收者读取时修改结构体。

English

Sending a pointer to a struct via channel, then modifying the struct in sender while receiver reads it.

generic

解决方案

  1. 95% 成功率 Send value instead of pointer
    ch := make(chan MyStruct)
    go func() {
        s := MyStruct{Field: 42}
        ch <- s // copy of s
    }()
    s := <-ch
  2. 85% 成功率 Use mutex to protect shared struct
    type Shared struct {
        mu sync.Mutex
        data MyStruct
    }
    var s Shared
    ch := make(chan *Shared)
    go func() {
        s.mu.Lock()
        s.data.Field = 42
        s.mu.Unlock()
        ch <- &s
    }()

无效尝试

常见但无效的做法:

  1. Assuming channel synchronization protects the data 90% 失败

    Channel synchronizes the send/recv operation, not the data pointed to.

  2. Copying pointer before send 80% 失败

    Copying pointer doesn't deep copy the struct; still shared.