Created
January 12, 2016 18:27
-
-
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.
This file contains 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() { | |
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