waitgroup.go 442 B

123456789101112131415161718192021222324252627282930
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. )
  7. func service(wg *sync.WaitGroup, instance int) {
  8. time.Sleep(2 * time.Second)
  9. fmt.Println("Service called on instance", instance)
  10. wg.Done()
  11. }
  12. func main() {
  13. wgExample()
  14. }
  15. func wgExample() {
  16. fmt.Println("main() started")
  17. var wg sync.WaitGroup
  18. for i := 1; i <= 3; i++ {
  19. wg.Add(1) // increment counter
  20. go service(&wg, i)
  21. }
  22. wg.Wait() // blocks here
  23. fmt.Println("main() stopped")
  24. }