go wait group

tags: learning go programming

content

  • we can use channel to block the main thread to achieve the goal of waiting
  • or we can use WaitGroup to wait for threads to finish
  • main thread needs to add each child thread into the WaitGroup
  • each child thread needs to update its done status when it’s done
  • WaitGroup needs to be passed by reference (pointer) to child threads
func worker(..., wg *sync.WaitGroup) {
	defer wg.Done()  // need to tell wg im done
	... do something
}
func main() {
	var wg sync.WaitGroup
	...
	go worker(..., &wg)
	wg.Wait()
}

up

go

down

reference