在go中,如何控制并发写入文本文件?
我问这个是因为我将有多个 goroutine 使用相同的文件处理程序写入文本文件。
我写了这段代码来尝试看看会发生什么,但我不确定我是否“正确”做到了:
package main
import (
"os"
"sync"
"fmt"
"time"
"math/rand"
"math"
)
func WriteToFile( i int, f *os.File, w *sync.WaitGroup ){
//sleep for either 200 or 201 milliseconds
randSleep := int( math.Floor( 200 + ( 2 * rand.Float64() ) ) )
fmt.Printf( "Thread %d waiting %d\n", i, randSleep )
time.Sleep( time.Duration(randSleep) * time.Millisecond )
//write to the file
fmt.Fprintf( f, "Printing out: %d\n", i )
//write to stdout
fmt.Printf( "Printing out: %d\n", i )
w.Done()
}
func main() {
rand.Seed( time.Now().UnixNano() )
d, err := os.Getwd()
if err != nil {
fmt.Println( err )
}
filename := d + "/log.txt"
f, err := os.OpenFile( filename, os.O_CREATE | os.O_WRONLY | os.O_TRUNC, 0666 )
if err != nil {
fmt.Println( err )
}
var w *sync.WaitGroup = new(sync.WaitGroup)
w.Add( 10 )
//start 10 writers to the file
for i:=1; i <= 10; i++ {
go WriteToFile( i, f, w )
}
//wait for writers to finish
w.Wait()
}
我一半期望输出会在文件中显示类似这样的内容,而不是我得到的连贯输出:
Printing Printing out: 2
out: 5
Poriuntitng: 6
从本质上讲,由于缺乏同步,我预计角色会出现不连贯和交织的情况。我是否没有编写代码来哄骗这种行为?或者在调用fmt.Fprintf同步写入过程中是否有某种机制?
慕田峪7331174
繁星coding
相关分类