What are WaitGroups in Golang?

Go ProgrammingServer Side ProgrammingProgramming

There may be instances in Golang where the execution of different goroutines may cause unexpected behaviour. In such cases, we want to make sure that certain goroutines work in a predefined manner and the program waits for all goroutines that are launched from the main function to wait. To do that, we use of WaitGroups.

WaitGroups allow us to tackle the problem mentioned above as they block the code until any goroutines within the WaitGroup has been successfully executed.

A WaitGroup has three exported methods that we make use of. These are −

  • Add(int) – Increases the counter.

  • Wait() – Blocks the execution until the internal counter becomes 0.

  • Done() – Decreases the counter by 1.

Example 1

Let's consider an example where we will use a gouroutine without any WaitGroups.

package main

import (
   "fmt"
)

func sumOfNumbers() {
   fmt.Println("Adding the numbers...")
}

func main() {
   fmt.Println("First")

   go sumOfNumbers()

   fmt.Println("Second")
}

Output

If we run the above code by using the command go run main.go, then we will get the following output −

First
Second

Notice, how we were not able to get the output of the function that was invoked in a goroutine. It's because the main function got terminated before it can execute that goroutine.

In order to solve this, we make use of WaitGroups which are used to block the program until any goroutines within that WaitGroup has successfully executed.

Example 2

Now, let's solve the above example with the help of WaitGroups. Consider the code shown below.

package main

import (
   "fmt"
   "sync"
)

func sumOfNumbers(wg *sync.WaitGroup) {
   fmt.Println("Adding the numbers...")
   wg.Done()
}

func main() {
   fmt.Println("First")

   var wg sync.WaitGroup

   wg.Add(1)

   go sumOfNumbers(&wg)

   wg.Wait()

   fmt.Println("Second")
}

Output

If we run the above code, it will produce the following output −

First
Adding the numbers...
Second

Example 3: WaitGroups in Anonymous Functions

We can also achieve the same as above in case we have an anonymous function that is running on a separate goroutine.

Consider the code shown below.

package main

import (
   "fmt"
   "sync"
)

func main() {
   fmt.Println("First")

   var wg sync.WaitGroup

   wg.Add(1)

   go func() {
      fmt.Println("Adding the numbers...")
      wg.Done()
   }()

   wg.Wait()

   fmt.Println("Second")
}

Output

If we run the above code by using the command go run main.go, then we will get the following output −

First
Adding the numbers...
Second
raja
Updated on 01-Nov-2021 07:36:26

Advertisements