Go语言-->sync.WaitGroup 详细解释

sync.WaitGroup 详细解释

sync.WaitGroup 是 Go 语言中用于同步多个 goroutine 的完成的工具。它允许主 goroutine 等待所有子 goroutine 执行完毕后再继续。

核心概念

WaitGroup 内部维护一个计数器

  • Add(n): 计数器加 n(通常在启动 goroutine 前调用)
  • Done(): 计数器减 1(在 goroutine 完成时调用)
  • Wait(): 阻塞直到计数器变为 0

基本用法

go 复制代码
package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	var wg sync.WaitGroup

	// 添加 3 个 goroutine 到等待组
	wg.Add(3)

	// 启动第一个 goroutine
	go func() {
		defer wg.Done() // 完成时计数器 -1
		fmt.Println("任务 1 开始")
		time.Sleep(1 * time.Second)
		fmt.Println("任务 1 完成")
	}()

	// 启动第二个 goroutine
	go func() {
		defer wg.Done()
		fmt.Println("任务 2 开始")
		time.Sleep(2 * time.Second)
		fmt.Println("任务 2 完成")
	}()

	// 启动第三个 goroutine
	go func() {
		defer wg.Done()
		fmt.Println("任务 3 开始")
		time.Sleep(500 * time.Millisecond)
		fmt.Println("任务 3 完成")
	}()

	// 等待所有 goroutine 完成
	wg.Wait()
	fmt.Println("所有任务完成!")
}

输出

复制代码
任务 1 开始
任务 2 开始
任务 3 开始
任务 3 完成
任务 1 完成
任务 2 完成
所有任务完成!

关键特性

方法 说明
Add(n) 计数器加 n,必须在启动 goroutine 前调用
Done() 计数器减 1,通常用 defer 确保执行
Wait() 阻塞直到计数器为 0

常见模式

1. 批量处理任务

go 复制代码
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
	wg.Add(1)
	go func(id int) {
		defer wg.Done()
		// 处理任务
		fmt.Printf("处理任务 %d\n", id)
	}(i)
}
wg.Wait()

注意事项

⚠️ 常见错误

  • Add() 调用晚于 goroutine 启动
  • 忘记调用 Done()
  • Wait() 前计数器已为 0

最佳实践

  • 使用 defer wg.Done() 确保执行
  • 在启动 goroutine 前调用 Add()
  • 避免在 goroutine 中调用 Add()
相关推荐
caimouse1 小时前
reactos编码规范
c语言·开发语言
xieliyu.5 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
星辰徐哥5 小时前
Spring Boot 微服务架构设计与实现
spring boot·后端·微服务
星辰徐哥5 小时前
Spring Boot 数据导入导出与报表生成
spring boot·后端·ui
明夜之约5 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee5 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Micro麦可乐5 小时前
Spring Boot 实战:从零设计一个短链系统(含完整代码与数据库设计)
数据库·spring boot·后端·哈希算法·雪花算法·短链系统
Jinkxs5 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
毕设源码_郑学姐5 小时前
计算机毕业设计springboot网络相册设计与实现 基于Spring Boot框架的在线相册管理系统开发与应用 Spring Boot驱动的网络影集设计与实践
spring boot·后端·课程设计
辣机小司5 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录