Basic usage of sync.WaitGroup

The main methods are as follows

method name Function
(wg * WaitGroup) Add(delta int) Calculator increases/decreases a certain number of times
(wg * WaitGroup) Done() Decrement the counter by 1, equivalent to wg.Add(-1)
(wg * WaitGroup) Wait() Block the program until the calculator reaches zero

Note that if calling wg.Add(delta) or wg.Done() changes the count maintained by wg to a negative number, a panic will occur.

package main

import (
    "fmt"
    "sync"
)

func worker(id int, wg *sync.WaitGroup) {
    
    
    defer wg.Done()

    fmt.Printf("Worker %d starting\n", id)
    // do some work
    fmt.Printf("Worker %d done\n", id)
}

func main() {
    
    
    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
    
    
        wg.Add(1)
        go worker(i, &wg)
    }

    wg.Wait()
    fmt.Println("All workers done")
}

Guess you like

Origin blog.csdn.net/weixin_37909391/article/details/130853859