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/

golang 的 sync.WaitGroup的更多相关文章

  1. Golang的sync.WaitGroup 实现逻辑和源码解析

    在Golang中,WaitGroup主要用来做go Routine的等待,当启动多个go程序,通过waitgroup可以等待所有go程序结束后再执行后面的代码逻辑,比如: func Main() { ...

  2. golang的sync.WaitGroup使用示例

    下面一段代码 len(m) 不一定会打印为 10,为什么?.如果想要 len(m) 打印为 10,应该怎么修改代码? func main() { const N = 10 m := make(map[ ...

  3. golang 中 sync包的 WaitGroup

    golang 中的 sync 包有一个很有用的功能,就是 WaitGroup 先说说 WaitGroup 的用途:它能够一直等到所有的 goroutine 执行完成,并且阻塞主线程的执行,直到所有的 ...

  4. Golang Sync.WaitGroup 使用及原理

    Golang Sync.WaitGroup 使用及原理 使用 func main() { var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.A ...

  5. golang sync.WaitGroup

    //阻塞,直到WaitGroup中的所以过程完成. import ( "fmt" "sync" ) func wgProcess(wg *sync.WaitGr ...

  6. Golang sync.WaitGroup的用法

    0x01 介绍 经常会看到以下了代码: 12345678910111213 package main import ( "fmt" "time") func m ...

  7. Go并发控制之sync.WaitGroup

    WaitGroup 会将main goroutine阻塞直到所有的goroutine运行结束,从而达到并发控制的目的.使用方法非常简单,真心佩服创造Golang的大师们! type WaitGroup ...

  8. golang-----golang sync.WaitGroup解决goroutine同步

    go提供了sync包和channel来解决协程同步和通讯.新手对channel通道操作起来更容易产生死锁,如果时缓冲的channel还要考虑channel放入和取出数据的速率问题. 从字面就可以理解, ...

  9. sync.WaitGroup的使用以及坑

    all goroutines are asleep - deadlock 简单使用: package main import ( "sync" ) type httpPkg str ...

随机推荐

  1. ubuntu下apache2使用的简单总结

        一. 修改apache2原80端口为90端口 1. 修改/etc/apache2/ports.conf, 将端口80改为90,443,改为444 2. 修改/etc/apache2/sites ...

  2. nginx配置文件中,location字段里面的root字段和别名alias

    1. location里面的root例子 server{ listen ; server_name www.wzw.com; location /www { root /data/; //设置虚拟主机 ...

  3. Redis-Java 交互的应用

    一.首先介绍一下Redis Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结构,例如hashes, lists, sets等,同时支持数据持久化.除此 ...

  4. Common xaml controls(补交作业)

    Common xaml controls 常见的xaml控件: 先上一段代码,把他们基本都实现出来: <Grid Name="MyGrid"> <Button N ...

  5. iOS几个功能:1.摇一摇;2.震动;3.简单的摇动动画;4.生成二维码图片;5.发送短信;6.播放网络音频等

    有一个开锁的功能,具体的需求就类似于微信的“摇一摇”功能:摇动手机,手机震动,手机上的锁的图片摇动一下,然后发送开锁指令.需求简单,但用到了许多方面的知识. 1.摇一摇 相对这是最简单的功能了. 在v ...

  6. python中的类方法、静态方法、对象方法

    注:以下都是以公有为前提,私有方法只能在类内部调用,不需多讲. 1.对象方法 这种方法都有一个默认参数:self  这代表实例的这个对象 def __init__(self): print(" ...

  7. Word2Vec原理及代码

    一.Word2Vec简介 Word2Vec 是 Google 于 2013 年开源推出的一款将词表征为实数值向量的高效工具,采用的模型有CBOW(Continuous Bag-Of-Words,连续的 ...

  8. Protobuf底层存储原理

    参考官网, 序列化原理 底层二进制存储 message Test1 { optional int32 a = 1; } 并设置为a=150,序列化到一个文件中,查看文件,得到下面的二进制: 08 96 ...

  9. linux如何安装和启动mongdb

    1.下载安装包 下载地址: https://www.mongodb.com/dr/fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.9.tgz/dow ...

  10. FJOI2019 游记[大概是考完会解封?]

    Day -1 不知不觉就快省选了啊...从NOIP的爆炸到现在也已经过了两个月了啊... 因为高一没有封闭[划] 所以这些内容是翘了课[划]在机房写的 嘛...感觉自己还有好多东西不会啊……这两天一直 ...