CodeFun Go

代码 WaitGroup 等待多个协程完成

想要等待多个协程完成,我们可以使用sync.WaitGroup

声明

var wg sync.WaitGroup

递增 WaitGroup 计数器

wg.Add(n)

通知 WaitGroup 任务完成

wg.Done()

阻塞直到WaitGroup 计数器归零

wg.Wait()
package main

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

func worker(id int, wg *sync.WaitGroup) {
	defer wg.Done()
	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 := 0; i <= 3; i++ {
		wg.Add(1)
		go worker(i, &wg)
	}
	wg.Wait()
}
worker 0 starting
worker 3 starting
worker 1 starting
worker 2 starting
worker 2 done
worker 0 done
worker 1 done
worker 3 done