go runtime_error ai_generated true

警告:数据竞争:协程X写入,协程Y读取(通道关闭)

WARNING: DATA RACE: Write by goroutine X, Read by goroutine Y (channel close)

ID: go/goroutine-racy-channel-close

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

版本兼容性

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

根因分析

多个协程试图关闭同一个通道而没有同步,导致竞争。

English

Multiple goroutines trying to close the same channel without synchronization, causing race.

generic

解决方案

  1. 95% 成功率 Use sync.Once to ensure close is called only once
    var once sync.Once
    once.Do(func() { close(ch) })
  2. 85% 成功率 Use a dedicated closer goroutine
    closeCh := make(chan struct{})
    go func() {
        <-closeCh
        close(ch)
    }()
    // signal close
    close(closeCh)

无效尝试

常见但无效的做法:

  1. Using atomic flag to guard close 80% 失败

    Close itself is not atomic; still race between check and close.

  2. Using recover() to catch double close panic 90% 失败

    Recover doesn't prevent race; panic may still occur.