Skip to content

WaitGroup

https://gobyexample-cn.github.io/waitgroups

go
package main

import (
    "fmt"
    "sync"
    "time"
)

func worker(id int) {
    fmt.Printf("Worker %d starting\n", id)

    time.Sleep(time.Second)
    fmt.Printf("Worker %d done\n", id)
}

func main() {

    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
        wg.Add(1) // wg 计数器 +1

        j := i

        go func() {
            defer wg.Done() // wg 计数器 -1
            worker(j)
        }()
    }

    wg.Wait() // 等到 计数器 == 0

}