O'Reilly logo

Go Standard Library Cookbook by Radomir Sohlich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Open the console and create the folder chapter06/recipe04.
  2. Navigate to the directory.
  3. 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 {            wg.Add(1)            go func(greetings string) {              fmt.Fprintln(wr, greetings)              wg.Done()            }(val)          }          wg.Wait()        }
  1. Execute the code by running go run syncwrite.go in the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required