# 恐慌：运行时错误：打开的文件过多（在 goroutine 中）

- **ID:** `go/too-many-open-files-in-goroutine`
- **领域:** go
- **类别:** io_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

goroutine 打开了大量文件描述符但没有关闭，耗尽了系统限制。这可能在处理大量连接或文件的并发程序中发生。

## 版本兼容性

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

## 解决方案

1. **Use a semaphore to limit concurrent file operations** (90% 成功率)
   ```
   sem := make(chan struct{}, 10) // limit 10 concurrent opens
for i := 0; i < 100; i++ {
    go func() {
        sem <- struct{}{}
        defer func() { <-sem }()
        f, err := os.Open("file.txt")
        if err != nil {
            log.Fatal(err)
        }
        defer f.Close()
        // process file
    }()
}
   ```
2. **Ensure all files are closed in a timely manner** (95% 成功率)
   ```
   f, err := os.Open("file.txt")
if err != nil {
    return err
}
defer f.Close()
// use f
   ```

## 无效尝试

- **Increasing the system ulimit without fixing the code** — This only delays the problem; if the code doesn't close files properly, the new limit will also be exhausted eventually. (80% 失败率)
- **Using defer to close files but not handling errors** — defer ensures close is called, but if multiple goroutines open files concurrently, the defer may not execute quickly enough, leading to file descriptor exhaustion. (70% 失败率)
