婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

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

Golang中的sync.WaitGroup用法實例

熱門標簽:最短的地圖標注 ?兓? 谷歌便利店地圖標注 電梯外呼訪客系統(tǒng) 電銷機器人可以補救房產(chǎn)中介嗎 騰訊外呼系統(tǒng)價格 百度地圖標注搜索關鍵詞 成都呼叫中心外呼系統(tǒ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用法實例》,本文關鍵詞  Golang,中的,sync.WaitGroup,用法,;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Golang中的sync.WaitGroup用法實例》相關的同類信息!
  • 本頁收集關于Golang中的sync.WaitGroup用法實例的相關信息資訊供網(wǎng)民參考!
  • 推薦文章
    主站蜘蛛池模板: 武清区| 庐江县| 虎林市| 乐平市| 房产| 扎囊县| 措美县| 保康县| 和龙市| 德兴市| 七台河市| 郁南县| 措勤县| 航空| 菏泽市| 耒阳市| 日照市| 利辛县| 莱西市| 泰兴市| 诸城市| 嘉善县| 商洛市| 崇阳县| 察隅县| 阜阳市| 墨竹工卡县| 景泰县| 日喀则市| 仙游县| 临清市| 济源市| 尉氏县| 旌德县| 饶河县| 佛教| 资中县| 密山市| 庆城县| 临澧县| 克什克腾旗|