分享
  1. 首页
  2. 文章

golang 的 sync.WaitGroup

ghj1976 · · 8487 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

WaitGroup的用途:它能够一直等到所有的goroutine执行完成,并且阻塞主线程的执行,直到所有的goroutine执行完成。

官方对它的说明如下:

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.

sync.WaitGroup只有3个方法,Add(),Done(),Wait()。

其中Done()是Add(-1)的别名。简单的来说,使用Add()添加计数,Done()减掉一个计数,计数不为0, 阻塞Wait()的运行。

例子代码如下:

同时开三个协程去请求网页, 等三个请求都完成后才继续 Wait 之后的工作。

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()

或者下面的测试代码

用于测试 给chan发送 1千万次,并接受1千万次的性能。

package main

import (
"fmt"
"sync"
"time"
)

const (
num = 10000000
)

func main() {
TestFunc("testchan", TestChan)
}

func TestFunc(name string, f func()) {
st := time.Now().UnixNano()
f()
fmt.Printf("task %s cost %d \r\n", name, (time.Now().UnixNano()-st)/int64(time.Millisecond))
}

func TestChan() {
var wg sync.WaitGroup
c := make(chan string)
wg.Add(1)

go func() {
for _ = range c {
}
wg.Done()
}()

for i := 0; i < num; i++ {
c <- "123"
}

close(c)
wg.Wait()

}

参考:

http://www.liguosong.com/2014/05/06/golang-sync-waitgroup/


有疑问加站长微信联系(非本文作者)

本文来自:博客园

感谢作者:ghj1976

查看原文:golang 的 sync.WaitGroup

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
8487 次点击
1 回复 | 直到 2025年05月09日 13:34:57
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏