Golang Goroutine Waitgroup with Example

golang goroutine waitgroup

In the previous blog, we learned about Goroutines Syntax and Creation in Golang. This Time we will learn about Golang Goroutine Waitgroup present in sync package that helps us to synchronize the Golang Goroutines.

Golang Goroutine WaitGroup

The previous blog’s code works fine but there we have to manually wait for the main function to execute, we can, however, automate it using WaitGroup in Golang.

The WaitGroup function is available in the Golang sync package. This helps the goroutine to be synchronized.

Whenever a new goroutine is encountered we can execute add function available in WaitGroup to add it to goroutine stack. At the end of the goroutines, we will wait for the goroutine for its execution to end.

Lets see!

package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup = sync.WaitGroup{}

func routine() {
	fmt.Println("Golang Goroutine")
}

func main() {
	message := "Hello Go routine WaitGroup"
	wg.Add(1)
	go func(msg string) {
		fmt.Println(msg)
		wg.Done()
	}(message)
	message = "Message Changed"
	wg.Wait()
}

Output:

Hello Go routine WaitGroup

The Add function adds the number of goroutines to wait for and when the Done function is executed it reduces the counter by 1.

The WaitGroup function in this way synchronizes the main function and the anonymous function.

This is a better implementation as we certainly don’t know how much time the main function will take to execute and thus for how much sleep time to add to stop the main function.

Golang Multiple Goroutines

package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup = sync.WaitGroup{}
var ct int = 0

func hello() {
	fmt.Printf("Hello Go %v\n", ct)
	wg.Done()
}

func counter() {
	ct++
	wg.Done()
}

func main() {
	for i := 0; i < 5; i++ {
		wg.Add(2)
		go hello()
		go counter()
	}
	wg.Wait()
}

Output:

Hello Go 4
Hello Go 2
Hello Go 4
Hello Go 0
Hello Go 3

In the example of Multiple Goroutines, we are creating goroutines in a loop 5 times, and two goroutines are created in each loop, and hence a total of 10 goroutines are created.

The hello function prints “Hello Go” along with the counter value. The counter function increments the counter value by 1.

When the Goroutine function call WaitGroup’s Done function is encountered the function’s execution is over and the Goroutine counter is decremented by 1.

But, we find that the Output is not as we thought. The Golang Goroutines are not synchronized.

In order to Synchronize multiple Golang Goroutines, we will use mutexes in Golang, which we will learn in the next blog.

Learn more about Golang Goroutine Waitgroup from the official Documentation.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *