go runtime_error ai_generated true

恐慌:关闭已关闭的通道

panic: close of closed channel

ID: go/close-channel-twice

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

版本兼容性

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

根因分析

尝试关闭一个已经关闭的通道。

English

Attempting to close a channel that has already been closed.

generic

解决方案

  1. 95% 成功率 Use sync.Once to ensure close is called only once
    var closeOnce sync.Once
    closeOnce.Do(func() { close(ch) })
  2. 90% 成功率 Design with a single producer that closes the channel
    Only one goroutine should close the channel; use a dedicated closer goroutine.

无效尝试

常见但无效的做法:

  1. Checking if channel is closed before closing via a flag 80% 失败

    Race condition: two goroutines may both see the flag as false and attempt close.

  2. Using recover() to catch panic 70% 失败

    recover() catches panics but closing a closed channel is a programming error; better to prevent.