4000-520-616
欢迎来到免疫在线!(蚂蚁淘生物旗下平台)  请登录 |  免费注册 |  询价篮
主营:原厂直采,平行进口,授权代理(蚂蚁淘为您服务)
咨询热线电话
4000-520-616
当前位置: 首页 > 新闻动态 >
热卖商品
新闻详情
go语言WaitGroup用法 | 熊窝窝
来自 : www.baiyuxiong.com/?p=... 发布时间:2021-03-25

WaitGroup在go语言中,用于线程同步,单从字面意思理解,wait等待的意思,group组、团队的意思,WaitGroup就是指等待一组,等待一个系列执行完成后才会继续向下执行。

贴上google官方的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package main
import
fmt
sync
net/http

func main
var wg sync.WaitGroup
var urls = string
http://www.golang.org/ ,
http://www.google.com/ ,
http://www.baiyuxiong.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
fmt.Println url ;
url

// Wait for all HTTP fetches to complete.
wg.Wait
fmt.Println over ;

代码执行结果为:

1
2
3
4
http://www.baiyuxiong.com/
http://www.google.com/
http://www.golang.org/

从执行结果可看出:
1、取三个网址信息的时候,结果显示顺序与for循环的顺序没有必然关系。
2、三个goroutine全部执行完成后,wg.Wait()才停止等待,继续执行并打印出over字符。


WaitGroup在go语言中,用于线程同步,单从字面意思理解,wait等待的意思,group组、团队的意思,WaitGroup就是指等待一组,等待一个系列执行完成后才会继续向下执行。go语言WaitGroup用法

本文链接: http://wait.immuno-online.com/view-740661.html

发布于 : 2021-03-25 阅读(0)
公司介绍
品牌分类
联络我们
服务热线:4000-520-616
(限工作日9:00-18:00)
QQ :1570468124
手机:18915418616
官网:http://