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

- **ID:** `go/goroutine-send-on-closed-channel`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

向已经关闭的通道发送数据，通常是由于多个协程发送数据时没有正确同步通道的关闭操作。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.21 | active | — | — |
| 1.22 | active | — | — |

## 解决方案

1. **Use a sync.Mutex to coordinate sends and close** (95% 成功率)
   ```
   var mu sync.Mutex
ch := make(chan int)
closeCh := func() {
    mu.Lock()
    defer mu.Unlock()
    close(ch)
}
send := func(v int) {
    mu.Lock()
    defer mu.Unlock()
    ch <- v
}
   ```
2. **Use a select with default to avoid send on closed channel** (90% 成功率)
   ```
   select {
case ch <- v:
default:
    // handle failure or retry
}
   ```

## 无效尝试

- **Checking channel state with a flag before sending** — Race condition: the channel could be closed between the check and the send, leading to a panic. (75% 失败率)
- **Using recover() to catch the panic and continue** — Recovering from a panic does not prevent data loss or corruption, and the program state may be inconsistent. (85% 失败率)
