ಮಿಥುನ್
Posted on August 14, 2020
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.
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")
}
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
- import "sync" package and declare variable sync.WaitGroup
- increment counter by using function Add(numberOfGroutineAdding)
- use Wait() at the end of program
- 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()
}
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.
Posted on August 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 25, 2024