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
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.
解决方案
-
95% 成功率 Use sync.Once to ensure close is called only once
var once sync.Once once.Do(func() { close(ch) }) -
85% 成功率 Use a dedicated closer goroutine
closeCh := make(chan struct{}) go func() { <-closeCh close(ch) }() // signal close close(closeCh)
无效尝试
常见但无效的做法:
-
Using atomic flag to guard close
80% 失败
Close itself is not atomic; still race between check and close.
-
Using recover() to catch double close panic
90% 失败
Recover doesn't prevent race; panic may still occur.