Write to file at the same time

In go, how can I control parallel writing to a text file?

I am asking about this because I will have several goroutines writing to a text file using the same file handler.

I wrote this bit of code to try to see what happens, but I'm not sure that I did this “correctly”:

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()

}

I expected the output to show something like this in the file instead of the resulting coherent output:

Printing Printing out: 2
out: 5
Poriuntitng: 6

Essentially, I expected the characters to come out incoherently and intertwined due to lack of synchronization. Didn't I write code to convince this behavior? Or is there some kind of mechanism during fmt.Fprintfwrite synchronization calls ?

+4
source share
2 answers

. - Mutex:

var mu sync.Mutex

func WriteToFile( i int, f *os.File, w *sync.WaitGroup ){
    mu.Lock()
    defer mu.Unlock()
    // etc...
}

, , Go , ( ):

POSIX.1-2008/SUSv4 XSI 2.9.7 ( " " ):

     , POSIX.1-2008,      :...

API - write() writev (2).    , (   ) - . Linux    3.14, : ,    (. open (2)) write() ( writev (2))    -    ,    () .    ​​ Linux 3.14.

, Go . ( , , )

+6

goroutine, . goroutine . , , - .

. , . .

Mutex , . CSP .

+13

All Articles