Getting Started with WaitGroups in Go

Introduction to WaitGroups in Go

In Go, the sync package provides synchronization primitives for concurrent code. One of the most commonly used synchronization tools is the WaitGroup which allows you to wait for a collection of goroutines to finish executing before proceeding further. This tutorial will cover how to use WaitGroup effectively in your Go programs.

What is a WaitGroup?

A WaitGroup is a struct provided by the sync package in Go. It's used to wait for a collection of goroutines to finish executing. The WaitGroup keeps track of how many goroutines are currently running and provides a mechanism to wait until all of them have completed their execution.

Using WaitGroup

To use a WaitGroup in your Go program, you need to follow these steps:

  1. Create a new WaitGroup.
  2. Add the number of goroutines you want to wait for by calling the Add method.
  3. Start your goroutines.
  4. At the end of each goroutine, call the Done method to indicate that it has completed its execution.
  5. Finally, call the Wait method on the WaitGroup to block until all goroutines have finished.

Let's walk through an example to illustrate how this works:

package main

import (
    "fmt"
    "sync"
)

func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done() // Decrements the WaitGroup counter when the function completes

    fmt.Printf("Worker %d starting\n", id)
    // Simulate some work
    for i := 0; i < 3; i++ {
        fmt.Printf("Worker %d: working...\n", id)
    }
    fmt.Printf("Worker %d done\n", id)
}

func main() {
    var wg sync.WaitGroup

    numWorkers := 5
    wg.Add(numWorkers) // Add the number of goroutines we want to wait for

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

    // Wait for all goroutines to finish
    wg.Wait()

    fmt.Println("All workers have finished")
}

In this example, we have a worker function that simulates some work by printing messages. In the main function, we create a new WaitGroup and add the number of goroutines we want to wait for using the Add method. Then, we start multiple goroutines, each calling the worker function. After starting all goroutines, we call the Wait method to block until all goroutines have finished executing.

Conclusion

WaitGroup is a useful tool for coordinating concurrent operations in Go. By using WaitGroup, you can ensure that certain tasks are completed before proceeding further in your program. Remember to call Add, Done, and Wait methods correctly to avoid race conditions and deadlocks in your concurrent code.


Similar Articles