《Go语言实战》笔记之协程同步 sync.WaitGroup

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

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>

转载于:https://www.cnblogs.com/zhouqi666/p/10247696.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值