Created
May 28, 2019 02:56
-
-
Save eliben/be8efeec5607700b89f97481008bf8b2 to your computer and use it in GitHub Desktop.
waitgroup example
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
Title: Waiting for goroutines to finish | |
URL slug: waitgroup | |
Description: A WaitGroup provides a simple way to wait for a collection of goroutines to perform a task. |
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" | |
) | |
// Important to pass wg by pointer | |
func worker(id int, wg *sync.WaitGroup) { | |
fmt.Printf("Worker %d starting\n", id) | |
time.Sleep(time.Duration(500+rand.Intn(500)) * time.Millisecond) | |
fmt.Printf("Worker %d done\n", id) | |
wg.Done() | |
} | |
func main() { | |
var wg sync.WaitGroup | |
for i := 1; i <= 10; i++ { | |
wg.Add(1) | |
go worker(i, &wg) | |
} | |
wg.Wait() | |
// All workers are done here. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment