使用同步的WaitGroup来等待所有的goroutines完成后再进行的代码示例

193 阅读1分钟

如果你正在运行多个goroutines,并希望在进行下一步之前等待所有的goroutines完成,你可以使用WaitGroup

package main

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

var wg sync.WaitGroup

func main() {
	teams := map[string]int{
		"Fenerbahce":  2,
		"Besiktas":    3,
		"Galatasaray": 0,
		"Trabzonspor": 4,
		"Altay":       1,
		"Bolu":        10,
	}

	wg.Add(len(teams))

	for k, v := range teams {
		go greet(k, v)
	}

	wg.Wait()
}

func greet(team string, delay int) {
	defer wg.Done()
	time.Sleep(time.Duration(delay) * time.Second)
	fmt.Println(team)
}
Galatasaray
Altay
Fenerbahce
Besiktas
Trabzonspor
Bolu