使用互斥锁或通道可避免Go中多goroutine写文件冲突。1. 互斥锁(sync.Mutex)确保同一时间仅一个goroutine写入;2. 通道(channel)将写请求序列化,由单一goroutine处理;3. 结合bufio.Writer可提升高并发写入性能。

在Go语言中,多个goroutine同时写入同一个文件会导致数据混乱或覆盖,必须通过同步机制避免冲突。最常用的方式是使用互斥锁(sync.Mutex)来保证同一时间只有一个goroutine能执行写操作。
通过引入 sync.Mutex,可以在写文件的临界区加锁,确保线程安全。
示例代码:
package main
<p>import (
"os"
"sync"
)</p><p>var (
file *os.File
mu sync.Mutex
wg sync.WaitGroup
)</p><p>func initFile(filename string) {
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
panic(err)
}
file = f
}</p><p>func writeData(data string) {
defer wg.Done()</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">mu.Lock()
defer mu.Unlock()
file.WriteString(data + "\n")}
立即学习“go语言免费学习笔记(深入)”;
func main() { initFile("output.txt") defer file.Close()
for i := 0; i < 10; i++ {
wg.Add(1)
go writeData("data from goroutine " + string(rune('0'+i)))
}
wg.Wait()}
另一种方式是将所有写请求发送到一个channel,由单独的goroutine顺序处理,从而避免竞争。
这种方式更适用于需要控制写入顺序或批量写入的场景。
示例:
package main
<p>import (
"bufio"
"os"
)</p><p>func writeFileWithChannel() {
messages := make(chan string, 10)
file, _ := os.Create("output.txt")
defer file.Close()</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">writer := bufio.NewWriter(file)
defer writer.Flush()
// 单独的写协程
go func() {
for msg := range messages {
writer.WriteString(msg + "\n")
}
}()
// 模拟多个生产者
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
messages <- "message from " + string(rune('0'+id))
}(i)
}
wg.Wait()
close(messages)}
两种方式各有适用场景:
基本上就这些,关键是不让多个goroutine直接操作同一个文件句柄。
以上就是Golang如何处理多goroutine写文件冲突的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号