Skip to content

Instantly share code, notes, and snippets.

@genghisjahn
Created January 12, 2016 18:27
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 genghisjahn/38cb1fb4202c8c089b1b to your computer and use it in GitHub Desktop.
Save genghisjahn/38cb1fb4202c8c089b1b to your computer and use it in GitHub Desktop.
Shows how to use a wait group to make sure all the go routines are done.
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func main() {
var tasks = []int{5, 2, 7, 4, 2, 9, 8}
var wg sync.WaitGroup
maind := random(100, 3000)
for _, v := range tasks {
go func(c int) {
wg.Add(1)
defer allDone(c)
d := random(500, 3000)
time.Sleep(time.Duration(d) * time.Millisecond)
fmt.Printf("%d + 1 = %d\n", c, c+1)
wg.Done()
}(v)
}
time.Sleep(time.Duration(maind) * time.Millisecond)
fmt.Println("Main process done.")
wg.Wait()
fmt.Println("All tasks complete!")
}
func allDone(c int) {
fmt.Println("All done with", c)
}
func random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment