golang 中 sync WaitGroup使用

本文介绍Go语言中sync.WaitGroup的使用方法及其应用场景。通过示例代码演示如何利用WaitGroup来控制goroutine的同步,确保所有子任务完成后再继续执行后续操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天写一些关于sync.WaitGroup的内容。

在golang中有两种方法可以实现同步机制

                  1.  无缓存的channel

                  2. WaitGroup

  WaitGroup 有3个方法: Add(),   Done(),   Wait()

Add()    增加计算器

Done()   计算器减1

Wait()   计算器非0 一直阻塞

测试代码:

func handle(data int) {

	fmt.Println(data)
	time.Sleep(time.Second * 6)
	fmt.Println("in handle")
}
func main() {
	var wg sync.WaitGroup
	wg.Add(16)
	for i := 0; i < 50; i++ {
		go func(data int) {
			handle(data)
			wg.Done()
		}(i)
	}
	fmt.Println("now wait.....")
	wg.Wait()

	fmt.Println("end")
}

结果如下:

now wait.....
49
0
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
in handle
in handle
in handle
in handle
in handle
in handle
in handle
in handle
in handle
in handle
in handle
in handle
in handle
in handle
in handle
in handle

end

从结果可以看出,当计算器为0时,后面整个进程就跑完退出了。所以 in handle 有16个,打印的数值却是 0~49,因为开始go  进入了handle,所以能从0~49能打印出来, 但是当Wait退出时,整个进程退出了。


使用场景:

        ------    当我需要处理大数据,需要将数据分割处理,然后聚合处理。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值