当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。