动态并发控制:sync.WaitGroup的灵活运用

简介: 动态并发控制:sync.WaitGroup的灵活运用

概述

在并发编程中,控制主程序等待所有 Goroutine 完成任务是一项关键任务。Go 语言提供了 sync.WaitGroup 来解决这一问题。

本文将讲解 sync.WaitGroup 的使用方法、原理以及在实际项目中的应用场景,用清晰的代码示例和详细的注释,助力读者掌握并发编程中等待组的使用技巧。


 

1. 基本使用

1

package main
import (  "fmt"  "sync"  "time")
func main() {  var wg sync.WaitGroup
  for i := 1; i <= 3; i++ {    wg.Add(1)    go worker(i, &wg)  }
  wg.Wait()  fmt.Println("All workers have completed.")}
func worker(id int, wg *sync.WaitGroup) {  defer wg.Done()
  fmt.Printf("Worker %d started\n", id)  time.Sleep(2 * time.Second)  fmt.Printf("Worker %d completed\n", id)}

在上面示例中,用一个 sync.WaitGroup 实例 wg,然后使用 wg.Add(1) 来增加计数,表示有一个 Goroutine 需要等待。

在每个 Goroutine 的结束处,使用 defer wg.Done() 来减少计数,表示一个 Goroutine 已完成。

最后,用 wg.Wait() 来等待所有 Goroutine 完成。

1.

package main
import (  "fmt"  "sync"  "time")
func main() {  var wg sync.WaitGroup
  for i := 1; i <= 3; i++ {    wg.Add(1)    go workerWithError(i, &wg)  }
  wg.Wait()  fmt.Println("All workers have completed.")}
func workerWithError(id int, wg *sync.WaitGroup) {  defer wg.Done()
  fmt.Printf("Worker %d started\n", id)  time.Sleep(2 * time.Second)
  // 模拟错误发生  if id == 2 {    fmt.Printf("Worker %d encountered an error\n", id)    return  }
  fmt.Printf("Worker %d completed\n", id)}

有时候,需要在 Goroutine 中处理错误。在这个示例中,当 id 为 2 时,模拟了一个错误的情况。

通过在错误发生时提前返回,可以确保计数正确减少,避免等待组出现死锁。


 

2. 多级等待组

2.1

package main
import (  "fmt"  "sync"  "time")
func main() {  var outerWG sync.WaitGroup  var innerWG sync.WaitGroup
  for i := 1; i <= 2; i++ {    outerWG.Add(1)    go outerWorker(i, &outerWG, &innerWG)  }
  outerWG.Wait()  fmt.Println("All outer workers have completed.")}
func outerWorker(id int, outerWG, innerWG *sync.WaitGroup) {  defer outerWG.Done()
  fmt.Printf("Outer Worker %d started\n", id)
  for j := 1; j <= 3; j++ {    innerWG.Add(1)    go innerWorker(id, j, innerWG)  }
  innerWG.Wait()  fmt.Printf("Outer Worker %d completed\n", id)}
func innerWorker(outerID, innerID int, wg *sync.WaitGroup) {  defer wg.Done()
  fmt.Printf("Inner Worker %d of Outer Worker %d started\n", innerID, outerID)  time.Sleep(2 * time.Second)  fmt.Printf("Inner Worker %d of Outer Worker %d completed\n", innerID, outerID)}

在示例中,使用了嵌套的 sync.WaitGroup。

外部的等待组 outerWG 等待所有外部 Goroutine 完成,而每个外部 Goroutine 内部的 innerWG 则等待其内部的所有 Goroutine 完成。

2.

package main
import (  "fmt"  "sync"  "time")
func main() {  var dynamicWG sync.WaitGroup
  for i := 1; i <= 3; i++ {    dynamicWG.Add(1)    go dynamicWorker(i, &dynamicWG)  }
  // 模拟动态添加更多任务  time.Sleep(1 * time.Second)    for i := 4; i <= 6; i++ {    dynamicWG.Add(1)    go dynamicWorker(i, &dynamicWG)  }
  dynamicWG.Wait()    fmt.Println("All dynamic workers have completed.")}
func dynamicWorker(id int, wg *sync.WaitGroup) {
  defer wg.Done()
  fmt.Printf("Dynamic Worker %d started\n", id)  time.Sleep(2 * time.Second)  fmt.Printf("Dynamic Worker %d completed\n", id)}

在上述示例中,创建了一个等待组 dynamicWG,然后在运行时动态添加了更多的任务。

用这种方式,可以动态地管理需要等待的 Goroutine 数量。


 

3. 超时处理

3.1


package main
import (  "fmt"  "sync"  "time")
func main() {
  var timeoutWG sync.WaitGroup
  for i := 1; i <= 3; i++ {    timeoutWG.Add(1)    go timeoutWorker(i, &timeoutWG)  }
  // 等待最多5秒,超时则不再等待  timeout := time.After(5 * time.Second)    done := make(chan struct{})
  go func() {    timeoutWG.Wait()    close(done)  }()
  select {  case <-done:    fmt.Println("All timeout workers have completed.")    case <-timeout:    fmt.Println("Timeout reached. Not all workers have completed.")  }}
func timeoutWorker(id int, wg *sync.WaitGroup) {  defer wg.Done()
  fmt.Printf("Timeout Worker %d started\n", id)    time.Sleep(time.Duration(id) * time.Second)    fmt.Printf("Timeout Worker %d completed\n", id)  }

在上面示例中,用 time.After 创建了一个 5 秒的超时通道。

在另一个 Goroutine 中监听等待组的完成情况,可以在超时或任务完成时得知等待的最终结果。

3.2

package main
import (  "errors"  "fmt"  "sync"  "time")
func main() {  var timeoutWG sync.WaitGroup
  for i := 1; i <= 3; i++ {    timeoutWG.Add(1)    go timeoutWorkerWithError(i, &timeoutWG)  }
  // 等待最多5秒,超时则返回错误  err := waitWithTimeout(&timeoutWG, 5*time.Second)
  if err != nil {    fmt.Printf("Timeout reached. Not all workers have completed. Error: %v\n", err)  } else {    fmt.Println("All timeout workers have completed.")  }}
func timeoutWorkerWithError(id int, wg *sync.WaitGroup) {  defer wg.Done()
  fmt.Printf("Timeout Worker %d started\n", id)  time.Sleep(time.Duration(id) * time.Second)
  // 模拟错误发生  if id == 2 {    fmt.Printf("Timeout Worker %d encountered an error\n", id)    return  }
  fmt.Printf("Timeout Worker %d completed\n", id)}
func waitWithTimeout(wg *sync.WaitGroup, timeout time.Duration) error {  done := make(chan struct{})
  go func() {    defer close(done)    wg.Wait()  }()
  select {  case <-done:    return nil      case <-time.After(timeout):    return errors.New("timeout reached")  }}

有时候,希望在程序超时的时候返回一个错误。

在这个示例中,用封装等待组的超时检查,可以在主程序中获得一个清晰的错误提示。


 

总结

通过讨论 sync.WaitGroup 的基本用法、避免常见错误以及实际应用,深入了解了这个强大的同步工具。

在 Go 语言并发编程中,合理使用 sync.WaitGroup 能够优雅地处理并发等待,确保主程序在所有任务完成后再继续执行。

目录
相关文章
|
4月前
|
人工智能 缓存 自然语言处理
能看能做能编程!通义千问Qwen3.7-Plus 打通 GUI+CLI 的全能 AI 助手
通义千问Qwen3.7-Plus是一款定位高性价比的多模态混合智能体模型,以35B稠密参数为基础,在强大文本能力之上,全面升级视觉理解、界面操作、代码生成与工具调用能力,实现“能看、能想、能动手”的端到端任务闭环。它打破传统多模态模型“仅能图文问答”的局限,原生融合GUI图形界面与CLI命令行交互,可自主感知屏幕、操作应用、编写代码、执行验证,成为面向开发、办公、行业数字化的工程级AI助手。本文从核心能力、技术参数、实战场景、API接入与成本优化等维度,全面解析Qwen3.7-Plus的功能与价值,附可直接使用的代码命令与配置示例。
581 1
|
网络协议 Linux C++
Linux C/C++ 开发(学习笔记十一 ):TCP服务器(并发网络网络编程 一请求一线程)
Linux C/C++ 开发(学习笔记十一 ):TCP服务器(并发网络网络编程 一请求一线程)
707 0
|
11月前
|
设计模式 人工智能 供应链
2026年智能体架构综述:从笨重设计到多智能体架构(MAS)
2024是智能体“前哨战”,2026则是生产级智能体的“分水岭”。告别笨重的单体设计,多智能体系统(MAS)正成为主流。通过“路由+执行者”架构与审计机制,实现专业分工、高效协作。AI不再只是工具,而是企业级操作系统,开启智能化协作新纪元。
1306 3
|
8月前
|
人工智能 自然语言处理 安全
Claude Code 全攻略:命令大全 + 实战工作流(建议收藏)
本文介绍了Claude Code终端AI助手的使用指南,主要内容包括:1)常用命令如版本查看、项目启动和更新;2)三种工作模式切换及界面说明;3)核心功能指令速查表,包含初始化、压缩对话、清除历史等操作;4)详细解析了/init、/help、/clear、/compact、/memory等关键命令的使用场景和语法。文章通过丰富的界面截图和场景示例,帮助开发者快速掌握如何通过命令行和交互界面高效使用Claude Code进行项目开发,特别强调了CLAUDE.md文件作为项目知识库的核心作用。
52855 73
Claude Code 全攻略:命令大全 + 实战工作流(建议收藏)
|
监控 负载均衡 安全
WebSocket网络编程深度实践:从协议原理到生产级应用
蒋星熠Jaxonic,技术宇宙中的星际旅人,以代码为舟、算法为帆,探索实时通信的无限可能。本文深入解析WebSocket协议原理、工程实践与架构设计,涵盖握手机制、心跳保活、集群部署、安全防护等核心内容,结合代码示例与架构图,助你构建稳定高效的实时应用,在二进制星河中谱写极客诗篇。
1053 5
WebSocket网络编程深度实践:从协议原理到生产级应用
|
人工智能 JavaScript 测试技术
Qwen3-Coder入门教程|10分钟搞定安装配置
Qwen3-Coder 挑战赛简介:无论你是编程小白还是办公达人,都能通过本教程快速上手 Qwen-Code CLI,利用 AI 轻松实现代码编写、文档处理等任务。内容涵盖 API 配置、CLI 安装及多种实用案例,助你提升效率,体验智能编码的乐趣。
40054 114
|
安全 JavaScript 网络协议
WebSocket通信协议基础原理与安全威胁
WebSocket通信协议基础原理与安全威胁
867 0