An Introduction to WaitGroups with Goroutines

An Introduction to WaitGroups with Goroutines

In Go, goroutines make concurrent programming efficient and straightforward, but managing multiple goroutines can sometimes feel tricky. That’s where WaitGroups come in! They’re a built-in tool that helps you coordinate the execution of goroutines, ensuring that all complete before moving on.


What is a WaitGroup?

A WaitGroup is a struct provided by Go’s sync package that allows you to wait for a collection of goroutines to finish executing. It’s a simple way to control goroutines without writing complex coordination code.

Using a WaitGroup in Action

To use a WaitGroup, you follow three basic steps:

  1. Add the number of goroutines to wait for.
  2. Run goroutines and call Done() inside each one after it completes.
  3. Call Wait() to block until all goroutines have called Done().

Here’s a quick example:

package main

import (
    "fmt"
    "sync"
)

func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done() // Signals that the goroutine is done
    fmt.Printf("Worker %d is starting...\n", id)
    // Simulate work
    fmt.Printf("Worker %d is done!!!\n", id)
}

func main() {
    var wg sync.WaitGroup
    numWorkers := 5

    for i := 1; i <= numWorkers; i++ {
        wg.Add(1)
        go worker(i, &wg)
    }

    wg.Wait() // Waits for all workers to complete
    fmt.Println("All workers have finished!!")
}        

?? How Does it Work?

  • Add(1) is called each time a new goroutine is launched, indicating another task to wait for.
  • Inside each goroutine, Done() signals the completion of that particular task.
  • Wait() pauses the main program until all added goroutines have completed.

?? Why Use WaitGroups?

  • Simple to Use: Provides an easy way to wait for multiple goroutines.
  • Safe and Efficient: Helps avoid race conditions when dealing with multiple tasks.
  • Essential for Synchronization: Ensures all background tasks are complete before moving forward.


?? In Summary: WaitGroups are a powerful way to coordinate goroutines in Go, making it easy to handle concurrent tasks with precision. If you’re working with Go’s concurrency model, mastering WaitGroups is a must for writing safe and efficient code!

#Golang #Concurrency #WaitGroups #GoProgramming #SoftwareDevelopment #TechTips #BackendEngineering

Vagner Nascimento

Software Engineer | Go (golang) | NodeJS (Javascrit) | AWS | Azure | CI/CD | Git | Devops | Terraform | IaC | Microservices | Solutions Architect

4 个月

Love this post Guilherme da Silva! Thanks for sharing!

回复
Lucas Wolff

.NET Developer | C# | TDD | Angular | Azure | SQL

4 个月

Great advice

回复
Sergio Paulo

Data Scientist | Python | LLM | GenAI | ML | RAG | NLP

4 个月

WaitGroups are essential for managing goroutines effectively in Go. Thanks!

回复
Leandro Veiga

Senior Software Engineer | Full Stack Developer | C# | .NET | .NET Core | React | Amazon Web Service (AWS)

4 个月

Great advice

要查看或添加评论,请登录

Guilherme da Silva的更多文章

社区洞察

其他会员也浏览了