原文地址(欢迎互换友链):

http://www.niu12.com/article/8

sync 包提供同步 goroutine 的功能

<p>文档介绍</p>
<code>
// 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.
//
// A WaitGroup must not be copied after first use.
翻译
一个WaitGroup等待一个goroutines集合的完成,
main(goroutines)调用Add()方法设置需要等到的goroutine熟练
然后执行每一个goroutine,并且完成时调用Done()方法
与此同时,Wait()方法可以用来锁住main(goroutines)直到所有goroutine完成 首次使用后不得复制WaitGroup
</code> <p>实例代码</p>
<code>
package main import (
"fmt"
"sync"
)
var wg sync.WaitGroup func printerOne(ch chan int) {
for i := range ch{
fmt.Printf("printerOne: %v\n" , i)
}
// 申明当前goroutine完成
wg.Done()
} func printerTwo(ch chan int) {
for i := range ch{
fmt.Printf("printerTwo: %v\n" , i) }
// 申明当前goroutine完成
wg.Done()
} func main() {
// 申明一个channel c
c := make(chan int) // 申明有两个goroutine需要执行
wg.Add(2) // 执行goroutine
go printerOne(c)
go printerTwo(c) // 向channel c发送数据
for i:=0; i < 10; i++ {
c <- i
}
// 关闭channel c
close(c)
// 等待goroutine全部完成
wg.Wait()
}
</code>

最新文章

  1. WPF入门教程系列二十三——DataGrid示例(三)
  2. Android Studio插件整理
  3. UVA 10474 大理石在哪 lower_bound
  4. 在eclipse中配置python插件
  5. HDU4686 Arc of Dream 矩阵快速幂
  6. 现代程序设计homework-02
  7. BASH内置变量
  8. Live555 实战之框架简单介绍
  9. HDU 2841 Visible Trees(莫比乌斯反演)
  10. 图解C#_事件
  11. mysql5.7.X版本only_full_group_by问题解决
  12. java 加密 解密 Illegal key size
  13. 安卓开发 Activity入门
  14. DHT11
  15. 一个将PDF转word、图片、PPT的在线工具
  16. MySQL 常用语法 之 UNION与UNION ALL
  17. Mac 10.12安装PDF浏览工具Foxit Reader
  18. 0511团队项目2.0--产品product backlog
  19. Machine Learning系列--归一化方法总结
  20. 【笔试题】Java 继承知识点检测

热门文章

  1. 3.Python3标准库--数据结构
  2. display:inline、block、inline-block三者之间的区别
  3. ASP .NET CORE 部署linux 系统上的所需要的sdk 使用链接
  4. Leetcode 之Wildcard Matching(32)
  5. leetcode 之Reorder List(25)
  6. ELK日志处理
  7. kubernetes如何要使用用户名和密码登陆harbor以拉取docker镜像,应该如何操作?
  8. 确实,k8s的时代,ingress负载用traefik比nginx方便啊
  9. 转:Python安全 - 从SSRF到命令执行惨案
  10. 洛谷——P1104 生日