Waitgroups in Golang

When doing concurrent programming in Go, it can be seen that the goroutine may not execute and the main thread stops before it finishes executing. This is a problem that frequently appears when doing concurrent programming. Waitgroups solves the problem in an easy way.

How Golang waitgroups work?

Waitgroup is a blocking mechanism that blocks when none of the goroutines which is inside that group has executed. If a goroutine is finished it then unblocks the group.

Golang Waitgroup example

Here is an example illustrating how to use a waitgroup with goroutine.

package main

import (
	"fmt"
	"sync"
)

// pass waitgroup as a pointer
func f(wg *sync.WaitGroup) {
	// do work
	fmt.Println("Working...")

	// call done
	wg.Done()
}

func main() {
	var wg sync.WaitGroup
        // add to the waitgroup counter
	wg.Add(1)

        // pass waitgroup as a pointer
	go f(&wg)

        // call wait
	wg.Wait()
	fmt.Println("Done working!")
}
Go Waitgroup
Golang Waitgroup

In the code above, we are first using the add function which tells the waitgroup how many goroutines to block for. Then we simply pass the group as a pointer to a goroutine. When the work is done by the goroutine we call the Done method that tells the waitgroup to stop blocking.

Waitgroups with the anonymous function

Waitgroups can be used with anonymous functions as well. It is really simple. Instead of using another function to call via goroutine we use anonymous function and do the same thing.

Here is an example.

package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		fmt.Println("Running anonymous function")
		wg.Done()
	}()
	wg.Wait()
	fmt.Println("Done executing")
}
Go Waitgroup Anonymous
Go Waitgroup Anonymous

As can be seen, it is pretty much the same for an anonymous function.

Importance of Go waitgroups

Golang Waitgroups are important because they allow a goroutine to block the thread and execute it. Without it, we need to manually sleep the main thread to let the goroutines execute. Waitgroups also can be used for different use cases that make it the most versatile way of handling goroutines execution.