當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO WaitGroup用法及代碼示例

GO語言"sync"包中"WaitGroup"類型的用法及代碼示例。

WaitGroup 等待一組 goroutine 完成。主 goroutine 調用 Add 來設置要等待的 goroutine 的數量。然後每個 goroutine 運行並在完成時調用 Done。同時,Wait 可以用來阻塞,直到所有的 goroutine 都完成。

首次使用後不得複製WaitGroup。

用法:

type WaitGroup struct {
    // contains filtered or unexported fields
}

例子:

此示例同時獲取多個 URL,使用 WaitGroup 進行阻塞,直到所有獲取完成。

package main

import (
	"sync"
)

type httpPkg struct{}

func (httpPkg) Get(url string) {}

var http httpPkg

func main() {
	var wg sync.WaitGroup
	var urls = []string{
		"http://www.golang.org/",
		"http://www.google.com/",
		"http://www.example.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()
}

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 WaitGroup。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。