Golang中的sync.WaitGroup用法實(shí)例
WaitGroup的用途:它能夠一直等到所有的goroutine執(zhí)行完成,并且阻塞主線程的執(zhí)行,直到所有的goroutine執(zhí)行完成。
官方對(duì)它的說明如下:
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個(gè)方法,Add(),Done(),Wait()。
其中Done()是Add(-1)的別名。簡(jiǎn)單的來說,使用Add()添加計(jì)數(shù),Done()減掉一個(gè)計(jì)數(shù),計(jì)數(shù)不為0, 阻塞Wait()的運(yùn)行。
例子代碼如下:
同時(shí)開三個(gè)協(xié)程去請(qǐng)求網(wǎng)頁(yè), 等三個(gè)請(qǐng)求都完成后才繼續(xù) 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()
或者下面的測(cè)試代碼
用于測(cè)試 給chan發(fā)送 1千萬(wàn)次,并接受1千萬(wàn)次的性能。
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() }
- 在golang中使用Sync.WaitGroup解決等待的問題
- Go并發(fā):使用sync.WaitGroup實(shí)現(xiàn)協(xié)程同步方式
- Go語(yǔ)言同步等待組sync.WaitGroup結(jié)構(gòu)體對(duì)象方法詳解
- GoLang的sync.WaitGroup與sync.Once簡(jiǎn)單使用講解
- 從并發(fā)到并行解析Go語(yǔ)言中的sync.WaitGroup
- Golang中的同步工具sync.WaitGroup詳解
- Go語(yǔ)言動(dòng)態(tài)并發(fā)控制sync.WaitGroup的靈活運(yùn)用示例詳解
- 深入理解go sync.Waitgroup的使用
相關(guān)文章
Go 1.22對(duì)net/http包的路由增強(qiáng)功能詳解
Go 1.22 版本對(duì) net/http 包的路由功能進(jìn)行了增強(qiáng),引入了方法匹配(method matching)和通配符(wildcards)兩項(xiàng)新功能,本文將給大家詳細(xì)的介紹一下Go 1.22對(duì)net/http包的路由增強(qiáng)功能,需要的朋友可以參考下2024-02-02golang使用excelize庫(kù)操作excel文件的方法詳解
Excelize是Go語(yǔ)言編寫的用于操作Office Excel文檔基礎(chǔ)庫(kù),基于ECMA-376,ISO/IEC 29500國(guó)際標(biāo)準(zhǔn),下面這篇文章主要給大家介紹了關(guān)于golang使用excelize庫(kù)操作excel文件的相關(guān)資料,需要的朋友可以參考下2022-11-11go HTTP2 的頭部壓縮算法hpack實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了go HTTP2 的頭部壓縮算法hpack實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10