的WaitGroup类型 同步 软件包,用于等待程序完成从主函数启动的所有goroutine。它使用一个指定goroutine数量的计数器,并且Wait阻止程序执行,直到WaitGroup计数器为零。
的 加 方法用于将计数器添加到WaitGroup。
的 完成了 使用defer语句来调度WaitGroup方法以减少WaitGroup计数器。
的 等待 等待Group类型的方法等待程序完成所有goroutine。
在主函数内部调用Wait方法,该函数将阻止执行,直到WaitGroup计数器的值为零为止,并确保所有goroutine都已执行。
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"同步"
)
// 等待Group is used to wait for the program to finish goroutines.
var wg 同步.WaitGroup
func responseSize(url string) {
// Schedule the call to 等待Group's 完成了 to tell goroutine is completed.
defer wg.Done()
fmt.Println("Step1: ", url)
response, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
fmt.Println("Step2: ", url)
defer response.Body.Close()
fmt.Println("Step3: ", url)
body, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println("Step4: ", len(body))
}
func main() {
// 加 a count of three, one for each goroutine.
wg.Add(3)
fmt.Println("Start Goroutines")
go responseSize("//www.yfmac.net")
go responseSize("//stackoverflow.com")
go responseSize("//coderwall.com")
// 等待 for the goroutines to finish.
wg.Wait()
fmt.Println("Terminating Program")
}
运行上面的程序时,您可能会看到以下输出:
C:\彩票中心下载\goroutines\create-simple-goroutine>go run main.go
Start Goroutines
Step1: //coderwall.com
Step1: //www.golangprograms.com
Step1: //stackoverflow.com
Step2: //stackoverflow.com
Step3: //stackoverflow.com
Step4: 116749
Step2: //www.golangprograms.com
Step3: //www.golangprograms.com
Step4: 79801
Step2: //coderwall.com
Step3: //coderwall.com
Step4: 203842
Terminating Program