国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Golang > 正文

Golang中的sync.WaitGroup用法實例

2020-04-01 19:13:58
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了Golang中的sync.WaitGroup用法實例,WaitGroup的用途,它能夠一直等到所有的goroutine執行完成,并且阻塞主線程的執行,直到所有的goroutine執行完成,需要的朋友可以參考下

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

例子代碼如下:

同時開三個協程去請求網頁, 等三個請求都完成后才繼續 Wait 之后的工作。

 

 
  1. var wg sync.WaitGroup  
  2. var urls = []string{  
  3. "http://www.golang.org/",  
  4. "http://www.google.com/",  
  5. "http://www.somestupidname.com/",  
  6. }  
  7. for _, url := range urls {  
  8. // Increment the WaitGroup counter.  
  9. wg.Add(1)  
  10. // Launch a goroutine to fetch the URL.  
  11. go func(url string) {  
  12. // Decrement the counter when the goroutine completes.  
  13. defer wg.Done()  
  14. // Fetch the URL.  
  15. http.Get(url)  
  16. }(url)  
  17. }  
  18. // Wait for all HTTP fetches to complete.  
  19. wg.Wait() 

或者下面的測試代碼

用于測試 給chan發送 1千萬次,并接受1千萬次的性能。

 

 
  1. package main 
  2.  
  3. import (  
  4. "fmt"  
  5. "sync"  
  6. "time"  
  7.  
  8. const (  
  9. num = 10000000  
  10.  
  11. func main() {  
  12. TestFunc("testchan", TestChan)  
  13.  
  14. func TestFunc(name string, f func()) {  
  15. st := time.Now().UnixNano()  
  16. f()  
  17. fmt.Printf("task %s cost %d /r/n", name, (time.Now().UnixNano()-st)/int64(time.Millisecond))  
  18.  
  19. func TestChan() {  
  20. var wg sync.WaitGroup  
  21. c := make(chan string)  
  22. wg.Add(1) 
  23.  
  24. go func() {  
  25. for _ = range c {  
  26. }  
  27. wg.Done()  
  28. }() 
  29.  
  30. for i := 0; i < num; i++ {  
  31. c <- "123"  
  32.  
  33. close(c)  
  34. wg.Wait() 
  35.  

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 濮阳县| 蓬莱市| 雷波县| 正定县| 铁岭市| 清水河县| 饶阳县| 梓潼县| 安徽省| 长治县| 平湖市| 信宜市| 潮安县| 潜江市| 玉林市| 博白县| 明水县| 长子县| 江永县| 宜城市| 松桃| 天等县| 平和县| 峨边| 海淀区| 昆明市| 赤峰市| 许昌县| 平江县| 丰原市| 车险| 赫章县| 屏东市| 肥东县| 四子王旗| 疏附县| 龙南县| 贵定县| 延庆县| 乌兰察布市| 北票市|