脚本专栏 
首页 > 脚本专栏 > 浏览文章

Golang中的sync.WaitGroup用法实例

(编辑:jimmy 日期: 2024/5/4 浏览:3 次 )

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中channel使用的一些小技巧
下一篇:利用Go语言初步搭建一个web应用的教程
一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网