Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Global waitgroup for goroutines

  • sync
  • WaitGroup
  • Add
  • Wait
  • Done
package main

import (
	"fmt"
	"sync"
)

func count(n int, name string) {
	for i := 1; i <= n; i++ {
		fmt.Printf("%v %v\n", name, i)
	}
	wg.Done()

}

var wg sync.WaitGroup

func main() {
	fmt.Println("Start")

	wg.Add(1)

	go count(1000, "Apple")
	go count(5, "Banana")

	wg.Wait()
	fmt.Println("End")
}
Start
Banana 1
Banana 2
Banana 3
Banana 4
Banana 5
End