This recipe will show you how to safely write to the file from multiple goroutines.
Writing the file from multiple goroutines
How to do it...
- Open the console and create the folder chapter06/recipe04.
- Navigate to the directory.
- Create the syncwrite.go file with the following content:
package main
import (
"fmt"
"io"
"os"
"sync"
)
type SyncWriter struct {
m sync.Mutex
Writer io.Writer
}
func (w *SyncWriter) Write(b []byte) (n int, err error) {
w.m.Lock()
defer w.m.Unlock()
return w.Writer.Write(b)
}
var data = []string{
"Hello!"...