WaitGroup 會將main goroutine阻塞直到全部的goroutine運行結束,從而達到併發控制的目的。使用方法很是簡單,真心佩服創造Golang的大師們!golang
官網說明:一個WaitGroup鎖等待一個goroutines合集結束。main goroutine裏面調用Add方法設置須要等待的goroutines 數量,而後運行每個goroutine,而且當其結束時調用Done方法。同時,main goroutine 被鎖住直到全部的goroutines完成。併發
使用方法(官網Example):fetch
var wg sync.WaitGroup var urls = []string{ "http://www.golang.org/", "http://www.google.com/", "http://www.somestupidname.com/", } for _, url := range urls { // Increment the WaitGroup counter.
wg.Add(1) // Launch a goroutine to fetch the URL.
go func(url string) { // Decrement the counter when the goroutine completes.
defer wg.Done() // Fetch the URL.
http.Get(url) }(url) } // Wait for all HTTP fetches to complete.
wg.Wait()
任何放在wg.Wait() 後面的語句阻塞,直到全部的goroutine返回:google
package main import ( "fmt" "net/http" "sync" ) func main() { var wg sync.WaitGroup var urls = []string{ "http://www.golang.org/", "http://www.google.com/", "http://www.somestupidname.com/", } for _, url := range urls { // Increment the WaitGroup counter. wg.Add(1) // Launch a goroutine to fetch the URL. go func(url string) { // Decrement the counter when the goroutine completes. defer wg.Done() // Fetch the URL. http.Get(url) fmt.Println("我先幹活, 主程序等着我") }(url) } // Wait for all HTTP fetches to complete. wg.Wait() fmt.Println("應該最後纔出來") }