校园春色亚洲色图_亚洲视频分类_中文字幕精品一区二区精品_麻豆一区区三区四区产品精品蜜桃

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

Golang中的sync.WaitGroup用法實例

熱門標簽:最短的地圖標注 ?兓? 谷歌便利店地圖標注 電梯外呼訪客系統 電銷機器人可以補救房產中介嗎 騰訊外呼系統價格 百度地圖標注搜索關鍵詞 成都呼叫中心外呼系統平臺 浙江人工智能外呼管理系統

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 之后的工作。

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發送 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詳解(什么是系統調用)
  • Golang的os標準庫中常用函數的整理介紹
  • Golang 標準庫 tips之waitgroup詳解

標簽:紹興 七臺河 宜昌 邢臺 盤錦 雅安 眉山 上海

巨人網絡通訊聲明:本文標題《Golang中的sync.WaitGroup用法實例》,本文關鍵詞  Golang,中的,sync.WaitGroup,用法,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Golang中的sync.WaitGroup用法實例》相關的同類信息!
  • 本頁收集關于Golang中的sync.WaitGroup用法實例的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 深州市| 尚义县| 达孜县| 南靖县| 西丰县| 定南县| 仪陇县| 松溪县| 西乌珠穆沁旗| 新田县| 淅川县| 丹东市| 区。| 汾阳市| 兴仁县| 祁门县| 壤塘县| 嘉峪关市| 宜宾县| 忻城县| 姜堰市| 聂拉木县| 日照市| 崇信县| 三都| 前郭尔| 准格尔旗| 民乐县| 东丰县| 开平市| 天水市| 中西区| 赫章县| 东台市| 河津市| 旌德县| 乳山市| 呼图壁县| 特克斯县| 方正县| 宝丰县|