Skip to content

Instantly share code, notes, and snippets.

@eliben
Created May 28, 2019 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliben/be8efeec5607700b89f97481008bf8b2 to your computer and use it in GitHub Desktop.
Save eliben/be8efeec5607700b89f97481008bf8b2 to your computer and use it in GitHub Desktop.
waitgroup example
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.
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