go runtime_error ai_generated true

恐慌:关闭已关闭的通道

panic: close of closed channel

ID: go/channel-close-twice

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

版本兼容性

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

根因分析

尝试关闭已经关闭的通道,通常由于多个goroutine没有协调就关闭通道。

English

Attempting to close a channel that has already been closed, usually due to multiple goroutines closing without coordination.

generic

解决方案

  1. 95% 成功率
    Use sync.Once to ensure the channel is closed only once.
  2. 90% 成功率
    Have a single owner goroutine that is responsible for closing the channel.

无效尝试

常见但无效的做法:

  1. 90% 失败

    The panic is fatal and cannot be recovered; it will crash the program.

  2. 85% 失败

    Checking a flag is racy; the channel may be closed between the check and the close call.

  3. 60% 失败

    The mutex ensures only one goroutine closes, but it does not prevent closing an already closed channel if the logic is wrong.