Golang中的sync.WaitGroup用法實(shí)例
WaitGroup的用途:它能夠一直等到所有的goroutine執(zhí)行完成,并且阻塞主線程的執(zhí)行,直到所有的goroutine執(zhí)行完成。
官方對(duì)它的說(shuō)明如下:
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)單的來(lái)說(shuō),使用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()
}
相關(guān)文章
go 迭代string數(shù)組操作 go for string[]
這篇文章主要介紹了go 迭代string數(shù)組操作 go for string[],具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12
Go語(yǔ)言之ORM(對(duì)象關(guān)系映射)庫(kù)詳解
GORM是Go語(yǔ)言流行ORM庫(kù),支持多數(shù)據(jù)庫(kù)與結(jié)構(gòu)體映射表,具備鏈?zhǔn)紸PI、自動(dòng)遷移、關(guān)聯(lián)操作等功能,原倉(cāng)庫(kù)已歸檔,推薦使用GORMv2,性能優(yōu)化且API更清晰,適合快速開發(fā),不適用于性能極致需求2025-07-07
Go語(yǔ)言的結(jié)構(gòu)體還能這么用?看這篇就夠了
這篇文章主要為大家詳細(xì)介紹了Go語(yǔ)言結(jié)構(gòu)體的各個(gè)知識(shí)點(diǎn),最后還介紹了空結(jié)構(gòu)體的3種妙用。文中的示例代碼講解詳細(xì),希望對(duì)大家有所幫助2023-02-02
Go interface接口聲明實(shí)現(xiàn)及作用詳解
這篇文章主要為大家介紹了Go interface接口聲明實(shí)現(xiàn)及作用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03

