Skip to content

Instantly share code, notes, and snippets.

@dacr
Created March 28, 2025 09:01
Show Gist options
  • Save dacr/55cb85c133788f73516e0a182adc6da6 to your computer and use it in GitHub Desktop.
Save dacr/55cb85c133788f73516e0a182adc6da6 to your computer and use it in GitHub Desktop.
go routines wait group / published by https://github.com/dacr/code-examples-manager #2658bdd8-a0a8-4505-9f15-66b708edf49f/8011b9406efd73965e0883a5d3c92631a82f41d
/*?sr/bin/true; exec /usr/bin/env nix-shell -p go --run "go run $0" #*/
// summary : go routines wait group
// keywords : go, goroutines, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 2658bdd8-a0a8-4505-9f15-66b708edf49f
// created-on : 2025-03-27T15:17:01+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : nix-shell -p go --run "go run $file"
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func main() {
wg := sync.WaitGroup{}
for i := range 100 {
wg.Add(1)
go func() {
defer wg.Done() // ALWAYS FIRST !!!
sleepTime := time.Duration(10+rand.Intn(100)) * time.Millisecond
time.Sleep(sleepTime)
fmt.Println(i, sleepTime)
}()
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment