Go语言教程之边写边学:基础练习:如何使用WaitGroup将main函数的执行延迟到所有goroutines完成后

如果将WaitGroup结构添加到代码中,它可能会延迟main函数的执行,直到所有goroutine完成后。简单来说,它允许您设置一些必需的迭代,以便在允许应用程序继续之前从goroutine获得完整的响应。
Done递减WaitGroup计数器,直到WaitGroup计数器为零。

 

示例代码:

package main

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

type testConcurrency struct {
	min int
	max int
	country string
}

func printCountry(test *testConcurrency, groupTest *sync.WaitGroup) {	
	for i :=test.max ; i>test.min; i-- {	
			time.Sleep(1*time.Millisecond)			
			fmt.Println(test.country)
	}

	fmt.Println()
	groupTest.Done()	
}

func  main() {
	groupTest := new(sync.WaitGroup)
	
	japan := new(testConcurrency)
	china := new(testConcurrency)
	india := new(testConcurrency)

	japan.country = "Japan"
	japan.min = 0
	japan.max = 5

	china.country = "China"
	china.min = 0
	china.max = 5

	india.country = "India"
	india.min = 0
	india.max = 5

	go printCountry(japan, groupTest)
	go printCountry(china, groupTest)
	go printCountry(india, groupTest)

	groupTest.Add(3)
	groupTest.Wait()
}

输出:

Japan
India
China
India
Japan
China
Japan
India
China
India
Japan
China
Japan

India

China