DEV Community

ಮಿಥುನ್
ಮಿಥುನ್

Posted on • Updated on

why to use sync.WaitGroup in golang?

WaitGroup instance is available in sync package in golang. WaitGroup is required to force Main GoRoutine to wait all other GoRoutine complete their tasks.

Before we see how to use waitgroup lets discuss about Goroutines first.

what is Goroutine?

Goroutine is separate path of execution if you familiar with Java, it is same as thread.

By default there is will atleast one Goroutine in golang program, which i call as Main Goroutine as i come from java background.

On top of that you can create your own Goroutine which can be called as user defined Goroutines.

How to create Goroutine?

it is simple, just use prefix "go" to your function call.

eg :   go myTask() // creates a Goroutine.
Enter fullscreen mode Exit fullscreen mode

why we need WaitGroup? lets look at this example

package main
import "fmt"
func task(msg string) {
for i := 0 ; i < 10 ; i++ {
    fmt.Println(msg)
}
}

func main() {
    // we are creating two goroutine
    go task("first")
    go task("second")
}
Enter fullscreen mode Exit fullscreen mode

output : program exited

In the above example , we are creating two Goroutine but we are not making Main Goroutine to wait till "first" and "second" Goroutine completes. Now sync.WaitGroup comes into picture.

steps to use sync.WaitGroup

  1. import "sync" package and declare variable sync.WaitGroup
  2. increment counter by using function Add(numberOfGroutineAdding)
  3. use Wait() at the end of program
  4. use Done() when each Goroutine is completed. It decrements counter by 1.

Now working example with sync.WaitGroup

package main

import (
"fmt"
"sync"
)

func task(msg string, wg *sync.WaitGroup) {
for i := 0 ; i < 10 ; i++ {
    fmt.Println(msg)
}
wg.Done() // decrement counter
}

func main() {
    var wg sync.WaitGroup
    wg.Add(1) // incrment counter for "first"
    go task("first", &wg)
    wg.Add(1) // increment counter for "second"
    go task("second", &wg)
    // Main Goroutine will wait till "first" and "second" completes
    wg.Wait() 

}
Enter fullscreen mode Exit fullscreen mode

output: ten times "first" and "second" will be printed.

In the above program , we have added one more parameter sync.WaitGroup to call Done() when each Goroutine is completed.

Top comments (0)