How to use WaitGroup to delay execution of the main function until after all goroutines are complete.
If you add a WaitGroup struct to your code, it can delay execution of the main function until after all goroutines are complete. In simple terms, it lets you set a number of required iterations to get a completed response from the goroutines before allowing the application to continue.
Done decrements the WaitGroup counter. Wait blocks until the WaitGroup counter is zero.
Example
package main
import (
"fmt"
"time"
"sync"
)
type testConcurrency struct {
min int
max int
country string
}
func printCountry(test *testConcurrency, groupTest *sync.WaitGroup) {
for i :=test.max ; i>test.min; i-- {
time.Sleep(1*time.Millisecond)
fmt.Println(test.country)
}
fmt.Println()
groupTest.Done()
}
func main() {
groupTest := new(sync.WaitGroup)
japan := new(testConcurrency)
china := new(testConcurrency)
india := new(testConcurrency)
japan.country = "Japan"
japan.min = 0
japan.max = 5
china.country = "China"
china.min = 0
china.max = 5
india.country = "India"
india.min = 0
india.max = 5
go printCountry(japan, groupTest)
go printCountry(china, groupTest)
go printCountry(india, groupTest)
groupTest.Add(3)
groupTest.Wait()
}
Output
Japan
India
China
India
Japan
China
Japan
India
China
India
Japan
China
Japan
India
China
groupTest.Add(3) As we are running 3 functions asynchronously we have specified 3.
groupTest.Wait() This tell WaitGroup to wait, here we can't set manually number of goroutines that need to wait.
Most Helpful This Week
Unmarshalling dynamic JSON in Golang
Golang RESTful API using GORM and Gorilla Mux
This sample program demonstrates how to create multiple goroutines and how the goroutine scheduler behaves with three logical processors.
Code formatting and naming convention tools in Golang
Example of Interface with Type Embedding and Method Overriding in GO language
Go language Best practices to follow in 2023