A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished. -- 出自官方文档
func main() { var wg sync.WaitGroup // 声明一个WaitGroup变量 var urls = []string{ "http://www.baidu.org/", "http://www.alibaba.com/", "http://www.qq.com/", } for _, url := range urls { wg.Add(1) // WaitGroup的计数加1 // Launch a goroutine to fetch the URL. go func(url string) { defer wg.Done() // goroutinue完成后, WaitGroup的计数-1 // Fetch the URL. http.Get(url) fmt.Println(url); }(url) } // Wait for all HTTP fetches to complete. wg.Wait() // 等待所有goroutinue完成 }
func main() { var urls = []string{ "http://www.baidu.org/", "http://www.alibaba.com/", "http://www.qq.com/", } doneChannel := make(chan int, len(urls)) // 创建channel for _, url := range urls { // Increment the WaitGroup counter. // Launch a goroutine to fetch the URL. go func(url string) { // Decrement the counter when the goroutine completes. // Fetch the URL. http.Get(url) doneChannel <- 1 // 向channel里放入数据表示完成操作 fmt.Println(url); }(url) } // Wait for all HTTP fetches to complete. for i := 0; i < len(urls); i++{ <-doneChannel // 当可以取出len(urls)个数据时, 表示所有goroutinue都完成 } fmt.Printf("Finish..\n") }