圆月山庄资源网 Design By www.vgjia.com
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() }
圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com
暂无评论...
更新日志
2024年05月15日
2024年05月15日
- dnf龙袍套装属性与天空套对比
- 横山菁儿-三国志-燃烧的长江-1993-APE整轨
- [ABC唱片]-《李传韵-琴魂》[K2-018][K2CD]WAV+CUE
- 【ABC唱片】《黃河號子SACD-011》-WAV分轨
- 当《生化危机2:重制版》加入路径追踪:画面真实感显著提升!
- 《哈迪斯2》BOSS不让暂停惹恼玩家:我手柄没电了!
- 《美末》S2艾莉造型首曝:头发留长 成熟了不少
- 邰正宵.2024-重燃爱恋.贰Walk.On【福茂】【FLAC分轨】
- 叶凡.2007-相思【中唱】【WAV+CUE】
- 王永.1997-十二道金牌【鸿心工作室】【WAV+CUE】
- dnf110换装在哪刷
- dnf110新版buff换装在哪里做
- dnf110满级了去哪里刷史诗
- 群星2024《龙年精逊纯银CD[WAV+CUE]
- 刘月宁《扬琴独奏-木兰辞变奏曲》[FLAC+CUE]