Golang gorouting 并发控制 sync.WaitGroup 介绍与使用
生活随笔
收集整理的這篇文章主要介紹了
Golang gorouting 并发控制 sync.WaitGroup 介绍与使用
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
WaitGroup簡(jiǎn)稱同步組,用于等待goroutines結(jié)束的。
官方文檔:
type WaitGroupA 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.翻譯過(guò)來(lái)就是:WaitGroup用來(lái)等待goroutings退出,主進(jìn)程調(diào)用Add設(shè)置等待的協(xié)程數(shù)量,在協(xié)程里面結(jié)束的時(shí)候調(diào)用Done方法。Wait方法將會(huì)阻塞直到所有協(xié)程都調(diào)用Done方法退出。
WaitGroup不能被復(fù)制使用,可以以指針的方式傳遞。
func (wg *WaitGroup) Add(delta int) 增加wg計(jì)數(shù)器func (wg *WaitGroup) Done() wg計(jì)數(shù)器減一func (wg *WaitGroup) Wait() 等待直到wg計(jì)數(shù)器變?yōu)?用例:
// wg.go package mainimport ("fmt""sync" )func child(wg *sync.WaitGroup, i int) {fmt.Printf("child:%d, exit \n", i)wg.Done() }func main() {//定義一個(gè)WaitGroup變量var wg sync.WaitGroup//添加goroutingfor i := 0; i <= 5; i++ {wg.Add(1)go child(&wg, i)}//等待gorouting退出wg.Wait()fmt.Printf("all gorouting exit\n")return }運(yùn)行結(jié)果:
參考文檔:
1.?https://golang.org/pkg/sync/#WaitGroup
總結(jié)
以上是生活随笔為你收集整理的Golang gorouting 并发控制 sync.WaitGroup 介绍与使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: wireshark 抓包显示 TCP s
- 下一篇: golang 编译提示 cannot a