# 恐慌：关闭已关闭的通道

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

## 根因

对已关闭的通道调用close()，通常由于多个协程未经协调地关闭。

## 版本兼容性

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

## 解决方案

1. **Use sync.Once to ensure close is called only once** (95% 成功率)
   ```
   var once sync.Once
once.Do(func() { close(ch) })
   ```
2. **Use a closed flag with mutex** (90% 成功率)
   ```
   var mu sync.Mutex
var closed bool
mu.Lock()
if !closed {
    close(ch)
    closed = true
}
mu.Unlock()
   ```

## 无效尝试

- **Using recover() to catch panic and ignore** — Recover hides the error but doesn't prevent data race or inconsistent state. (80% 失败率)
- **Checking ch != nil before close** — A closed channel is not nil; nil check doesn't prevent double close. (100% 失败率)
