Writing the file from multiple goroutines
This recipe will show you how to safely write to 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!", "Ola!", "Ahoj!", } func main() { f, err := os.Create("sample.file") if err != nil { panic(err) } wr := &SyncWriter{sync.Mutex{}, f} wg := sync.WaitGroup{} for _, val := range data { ...