WaitGroup in Go

Go: WaitGroup

What is WaitGroup?

The WaitGroup is a struct in Go that allows a program to wait for a group of goroutines to complete their execution before continuing further. It provides a simple way to synchronize concurrent operations and avoid race conditions.

The WaitGroup struct has two methods: Add() and Done(). The Add() method increments the WaitGroup counter by a given value, while the Done() method decrements the counter by 1. The Wait() method blocks the program execution until the counter becomes zero.

How to use WaitGroup in Go?

Here is an example of using WaitGroup in Go:

    package main

    import (
        "fmt"
        "sync"
    )

    func worker(id int, wg *sync.WaitGroup) {
        defer wg.Done()

        fmt.Printf("Worker %d starting\n", id)

        // Do some work
        for i := 0; i < 5; i++ {
            fmt.Printf("Worker %d: %d\n", id, i)
        }

        fmt.Printf("Worker %d done\n", id)
    }

    func main() {
        var wg sync.WaitGroup

        // Add 3 workers to the WaitGroup
        for i := 1; i <= 3; i++ {
            wg.Add(1)
            go worker(i, &wg)
        }

        // Wait for all workers to complete
        wg.Wait()

        fmt.Println("All workers done")
    }

Explainations:

  • we create a WaitGroup wg and add 3 workers to it using the Add() method. Then, we launch each worker in a separate goroutine, passing the &wg pointer to each worker.
  • Each worker function simulates doing some work and then calls wg.Done() to decrement the WaitGroup counter by 1. Finally, the main function calls wg.Wait() to block until all workers have completed.

The output of this program might look something like this:

    Worker 1 starting
    Worker 2 starting
    Worker 3 starting
    Worker 1: 0
    Worker 3: 0
    Worker 2: 0
    Worker 3: 1
    Worker 2: 1
    Worker 1: 1
    Worker 2: 2
    Worker 3: 2
    Worker 1: 2
    Worker 3: 3
    Worker 2: 3
    Worker 1: 3
    Worker 2: 4
    Worker 3: 4
    Worker 1: 4
    Worker 1 done
    Worker 3 done
    Worker 2 done
    All workers done

As we can see, the workers are executed concurrently and the WaitGroup ensures that the main function does not exit until all workers have completed their work.

Previous Article

Next Article