WaitGroup 用于等待一组 goroutine 结束,用法很简单。它有三个方法:

func (wg *WaitGroup) Add(delta int)
func (wg *WaitGroup) Done()
func (wg *WaitGroup) Wait()

Add 用来添加 goroutine 的个数。Done 执行一次数量减 1。Wait 用来等待结束:

package main

import (
    "fmt"
    "sync"
)

var count int
var rw sync.RWMutex

func main() {
    var wg sync.WaitGroup
    seconds := map[int]int{
        0: 1,
        1: 2,
        2: 3,
        3: 100,
    }

    for i, s := range seconds {
        wg.Add(1)
        go func(i, s int) {
            defer wg.Done()
            fmt.Printf("gorotine%d 结束\n", i)
        }(i, s)
    }

    wg.Wait()
    fmt.Println("所有goroutine执行结束")
}

//输出
    gorotine1 结束
    gorotine2 结束
    gorotine3 结束
    gorotine0 结束
    所有goroutine执行结束

注意,wg.Add() 方法一定要在 goroutine 开始前执行哦。



登陆发表评论