go runtime_error ai_generated true

恐慌:向已关闭的通道发送数据

panic: send on closed channel

ID: go/panic-runtime-error-send-on-closed-channel

其他格式: JSON · Markdown 中文 · English
85%修复率
85%置信度
1证据数
2023-06-15首次发现

版本兼容性

版本状态引入弃用备注
go1.21 active
go1.22 active
go1.23 active

根因分析

尝试向已关闭的通道发送值,违反了通道的使用约定。

English

Attempting to send a value on a channel that has already been closed, which violates the channel contract.

generic

官方文档

https://go.dev/ref/spec#Close

解决方案

  1. Ensure the channel is closed only by the sender after all sends are complete. Use a sync.WaitGroup to coordinate goroutines, and close the channel in a dedicated goroutine after Wait.
  2. Use a select statement with a default case to check if the channel is closed before sending, or use a separate closed channel for signaling.

无效尝试

常见但无效的做法:

  1. Adding a time.Sleep before closing the channel to avoid race conditions. 85% 失败

    Race conditions are timing-dependent; adding sleep does not guarantee ordering and may hide the bug rather than fix it.

  2. Using recover() in a deferred function to catch the panic. 70% 失败

    Recovering from a panic does not fix the root cause; the channel was already misused and data may be lost.

  3. Closing the channel after all sends are done by adding a sync.WaitGroup but not calling WaitGroup.Wait() correctly. 60% 失败

    Incorrect WaitGroup usage leads to same race: close happens before all sends complete.