国产探花免费观看_亚洲丰满少妇自慰呻吟_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.  

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 内江市| 葫芦岛市| 营口市| 资兴市| 宜川县| 佛山市| 互助| 神木县| 城步| 高邑县| 醴陵市| 越西县| 于田县| 申扎县| 阜康市| 广东省| 石屏县| 钟祥市| 镇江市| 林甸县| 平和县| 德惠市| 泸水县| 通州区| 平果县| 定远县| 织金县| 龙江县| 正宁县| 任丘市| 商河县| 乐安县| 邹平县| 安岳县| 丹巴县| 龙胜| 清苑县| 思茅市| 长丰县| 汉中市| 汉中市|