# 致命错误：并发文件写入（日志文件）

- **ID:** `go/goroutine-racy-file-write`
- **领域:** go
- **类别:** io_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

多个协程同时写入同一个文件而没有同步，导致输出损坏。

## 版本兼容性

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

## 解决方案

1. **Use a mutex to serialize file writes** (95% 成功率)
   ```
   var mu sync.Mutex
f, _ := os.Create("log.txt")
mu.Lock()
f.Write([]byte("data"))
mu.Unlock()
   ```
2. **Use a dedicated goroutine to handle all writes via channel** (90% 成功率)
   ```
   ch := make(chan string)
go func() {
    f, _ := os.Create("log.txt")
    defer f.Close()
    for s := range ch {
        f.WriteString(s)
    }
}()
ch <- "log entry"
   ```

## 无效尝试

- **Using os.File.Write directly without lock** — File writes are not atomic; interleaved writes corrupt data. (90% 失败率)
- **Using bufio.Writer without synchronization** — Bufio.Writer buffers writes but still racy when flushing. (80% 失败率)
