How to sync goroutines in go? How to use wait groups?
First of all, to know more about goroutines, visit this blog for better understanding.
In realtime, we may start many goroutines in a program and we need to manage those goroutines efficiently to get the expected output. To sync those goroutines, waitgroups are commonly used in order to validate the fact that multiple goroutines have completed. We do this make sure we have completed all of the concurrent work that we expect to complete.
There are three main methods in waitgroups,
WaitGroup is one of the methods of “sync” package available in golang. Add, Done, Wait are three methods of waitgroup widely used for syncing goroutines.
Let’s initialize the waitgroup as below
var wg sync.WaitGroup
wg.Add(int) — Add method takes an integer as an argument. The integer indicates how many goroutines are added to the wg.
wg.Add(1) denotes that a goroutine is added to the waitgroup pointer.
wg.Done() decrements the pointer of waitgroup by 1 denoting that one of the goroutines has been executed.
wg.Wait() block the program until the counter attached to the wg becomes zero. Once the counter becomes zero, the next statement starts to executes.
Let’s see the usage of the above methods in the code below
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
func printName(name string, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Println("The name is %s", name)
}
func main() {
var wg sync.WaitGroup
var names= []string{"user1", "user2", "user3", "user4"}
for i := range names{
wg.Add(1)
go printName(names[i], &wg)
}
wg.Wait()
}
On running the code above we get an output like below
user1
user2
user3
user4
If you like this post, please do like and add your comments and follow my page for more go related blogs.