Skip to content

Instantly share code, notes, and snippets.

@teocci
Created March 5, 2023 16:13
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 teocci/b786326edec6bcc41377e89ba78c7ef0 to your computer and use it in GitHub Desktop.
Save teocci/b786326edec6bcc41377e89ba78c7ef0 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