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. leecode刷题(16)-- 字符串转换整数

    leecode刷题(16)-- 字符串转换整数 字符串转换整数 描述: 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格 ...

  2. LOJ#6046. 「雅礼集训 2017 Day8」爷(分块)

    题面 传送门 题解 转化为\(dfs\)序之后就变成一个区间加,区间查询\(k\)小值的问题了,这显然只能分块了 然而我们分块之后需要在块内排序,然后二分\(k\)小值并在块内二分小于它的元素--一个 ...

  3. linux系统无法启动,提示give root password for maintenance错误

    电脑的虚拟机安装的是centos6.2操作系统,今天打开虚拟机时候,提示 give root password for maintenance (or type control-D to contin ...

  4. 查看npm全局安装位置

    查看npm全局安装位置:npm config get prefix 设置位置:npm config set prefix 填写位置

  5. linuxea:ELK5.5-elasticsearch-x-pack破解

    本站采用知识共享署名-非商业性使用-相同方式共享国际许可协议4.0 进行许可 本文作者:www.linuxea.com for Mark 文章链接:https://www.linuxea.com/17 ...

  6. mysql 添加索引 mysql 如何创建索引

    1.添加PRIMARY KEY(主键索引) mysql>ALTER TABLE `table_name` ADD PRIMARY KEY ( `column` ) 2.添加UNIQUE(唯一索引 ...

  7. [Objective-C语言教程]日志处理(21)

    为了打印日志,可使用Objective-C编程语言中的NSLog方法,首先在HelloWorld示例中使用了这个方法. 下面来看一下打印“Hello World”字样的简单代码 - #import & ...

  8. 爬虫7:selenium

    1. 一个简单的使用例子 from selenium import webdriver from selenium.webdriver.common.by import By from seleniu ...

  9. 继承Runnable 实现Synchronized 同步锁

    在java编程中,经常需要用到同步,而用得最多的也许是synchronized关键字了,下面看看这个关键字的用法. 因为synchronized关键字涉及到锁的概念,所以先来了解一些相关的锁知识. j ...

  10. docker安装Tomcat软件,部署项目

    1 搜索tomcat镜像 $ sudo docker search tomcat NAME DESCRIPTION STARS OFFICIAL AUTOMATED tomcat Apache Tom ...