golang中的sync.WaitGroup的使用

1.使用解释

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()的运行。

2.使用实例:

func main() {
wg := new(sync.WaitGroup)

p := new(ProducerImpl)
c := new(ConsumerImpl)

b := &Basket {
list.New(),
}

wg.Add(2) //添加一共添加了多少个协程
go func() {
p.makeDuck(b)
wg.Done() //执行完一个协程,计数器里协程的总量就减少一个
}()

go func() {
c.buyDuck(b)
wg.Done()
}()
wg.Wait() //计数器总量 > 0时, 主协程会一致阻塞,直到所有的子协程执行完后,主协程再退出
}
posted @ 2019-02-21 00:00  Soren  阅读(344)  评论(0)    收藏  举报