Created
March 20, 2018 08:14
-
-
Save paulja/4ad7e9943cfd515fb4ca34f16b5b0e9d to your computer and use it in GitHub Desktop.
Simple synchronisation block example in Go by using a WaitGroup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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