Example of the use of sync.WaitGroup in Golang

  • 2020-05-30 20:23:16
  • OfStack

Purpose of WaitGroup: it can wait until all goroutine executions are completed, and block the execution of the main thread until all goroutine executions are completed.

The official explanation is as follows:

A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.

sync.WaitGroup has only three methods, Add(), Done(), Wait().

Where Done() is the alias for Add(-1). Simply put, Add() is used to add a count, Done() is used to subtract a count, the count is not zero, and Wait() is blocked.

The example code is as follows:

At the same time, open three coroutines to request web pages, and continue the work after Wait after all three requests are completed.

var wg sync.WaitGroup 
var urls = []string{ 
for _, url := range urls { 
  // Increment the WaitGroup counter. 
  // Launch a goroutine to fetch the URL. 
  go func(url string) { 
    // Decrement the counter when the goroutine completes. 
    defer wg.Done() 
    // Fetch the URL. 
// Wait for all HTTP fetches to complete. 


Or the test code below

Used to test the performance of sending chan 10 million times and receiving 10 million times.

package main

import ( 

const ( 
  num = 10000000 

func main() { 
  TestFunc("testchan", TestChan) 

func TestFunc(name string, f func()) { 
  st := time.Now().UnixNano() 
  fmt.Printf("task %s cost %d \r\n", name, (time.Now().UnixNano()-st)/int64(time.Millisecond)) 

func TestChan() { 
  var wg sync.WaitGroup 
  c := make(chan string) 

  go func() { 
    for _ = range c { 

  for i := 0; i < num; i++ { 
    c <- "123" 



Related articles: