Skip to content

Instantly share code, notes, and snippets.

@evillemez
Created October 16, 2016 00:50
Show Gist options
  • Save evillemez/473d7201bd1869590a6f1776e56d116b to your computer and use it in GitHub Desktop.
Save evillemez/473d7201bd1869590a6f1776e56d116b to your computer and use it in GitHub Desktop.
Playing with WaitGroup in nested goroutines
package main
import (
"crypto/rand"
"fmt"
"math/big"
"os"
"sync"
"time"
)
// a little test of nested wait groups.... does it behave as I expect?
func main() {
numWorkers := 4
numTasks := 4
// start workers in goroutine
var workersWG sync.WaitGroup
for i := 0; i < numWorkers; i++ {
i := i
fmt.Println("Worker", i, ": START")
workersWG.Add(1)
go func() {
defer workersWG.Done()
// start tasks in worker
var tasksWG sync.WaitGroup
for j := 0; j < numTasks; j++ {
j := j
fmt.Println("Worker ", i, " | Task ", j, ": START")
tasksWG.Add(1)
go func() {
defer tasksWG.Done()
dur, _ := rand.Int(rand.Reader, big.NewInt(5000000000))
time.Sleep(time.Duration(dur.Int64()))
fmt.Println("Worker ", i, " | Task ", j, ": END")
}()
}
tasksWG.Wait()
time.Sleep(5000000000) //apparently this is 5 sec
fmt.Println("Worker", i, ": END")
}()
}
workersWG.Wait()
os.Exit(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment