sync.WaitGroup怎么在Golang中使用

发布时间:2021-01-20 16:00:51 作者:Leah
来源:亿速云 阅读:131

本篇文章为大家展示了sync.WaitGroup怎么在Golang中使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

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()

}

上述内容就是sync.WaitGroup怎么在Golang中使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. golang中如何使用defer
  2. golang中如何使用接口

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

golang sync.waitgroup

上一篇:深如何在PHP中使用JSONAPI

下一篇:怎么在vue中对config进行配置

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》