佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > Golang中的sync.WaitGroup用法實例

Golang中的sync.WaitGroup用法實例

熱門標簽:呼叫中心市場需求 AI電銷 網(wǎng)站排名優(yōu)化 Linux服務器 百度競價排名 地方門戶網(wǎng)站 服務外包 鐵路電話系統(tǒng)

WaitGroup的用途:它能夠一直等到所有的goroutine執(zhí)行完成,并且阻塞主線程的執(zhí)行,直到所有的goroutine執(zhí)行完成。

官方對它的說明如下:

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()添加計數(shù),Done()減掉一個計數(shù),計數(shù)不為0, 阻塞Wait()的運行。

 
例子代碼如下:

同時開三個協(xié)程去請求網(wǎ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()

 

或者下面的測試代碼

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

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 中使用WaitGroup的那點坑
  • 在golang中使用Sync.WaitGroup解決等待的問題
  • Golang中的sync包的WaitGroup操作
  • Golang標準庫syscall詳解(什么是系統(tǒng)調(diào)用)
  • Golang的os標準庫中常用函數(shù)的整理介紹
  • Golang 標準庫 tips之waitgroup詳解

標簽:湖南 蘭州 衡水 崇左 仙桃 湘潭 銅川 黃山

巨人網(wǎng)絡通訊聲明:本文標題《Golang中的sync.WaitGroup用法實例》,本文關鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    安阳市| 京山县| 盖州市| 阿克苏市| 修水县| 东丽区| 宁德市| 汽车| 北辰区| 抚顺市| 连州市| 霍林郭勒市| 榆林市| 含山县| 广西| 光山县| 福清市| 柘城县| 绥化市| 甘德县| 特克斯县| 尉犁县| 丹寨县| 呈贡县| 榆中县| 镇康县| 石林| 江华| 白河县| 英德市| SHOW| 峨边| 长葛市| 岗巴县| 皮山县| 吴桥县| 东兴市| 胶南市| 长武县| 金昌市| 佛坪县|