Skip to content

Instantly share code, notes, and snippets.

@paulja
Created March 20, 2018 08:14
Show Gist options
  • Save paulja/4ad7e9943cfd515fb4ca34f16b5b0e9d to your computer and use it in GitHub Desktop.
Save paulja/4ad7e9943cfd515fb4ca34f16b5b0e9d to your computer and use it in GitHub Desktop.
Simple synchronisation block example in Go by using a WaitGroup
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func main() {
// simple sync wait... queue work and wait for them all to finish
wg := sync.WaitGroup{}
for i := 0; i < 5; i++ {
wg.Add(1) // note we add BEFORE starting the Goroutine
go func(i int) {
time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
fmt.Println(i)
wg.Done()
}(i)
}
wg.Wait()
fmt.Println("done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment