go io_error ai_generated true

fatal error: concurrent file writes (log file)

ID: go/goroutine-racy-file-write

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2025-10-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.22 active

Root Cause

Multiple goroutines writing to the same file without synchronization, causing corrupted output.

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. Using os.File.Write directly without lock 90% fail

    File writes are not atomic; interleaved writes corrupt data.

  2. Using bufio.Writer without synchronization 80% fail

    Bufio.Writer buffers writes but still racy when flushing.