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
Program to print full pyramid using star
Golang write CSV records
How to check specific field exist in struct?
How to Convert string to integer type in Go?
How do you handle HTTP client server logging in Go?
How to create Slice using Make function in Golang?
Golang read csv file into struct
How to build a map of struct and append values to it?
Is There Still a Need for Programming in This AI World?
How to convert Boolean Type to String in Go?