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
Implementing interface from different package golang
This sample program demonstrates how to decode a JSON string.
Golang read file line by line to string
Code formatting and naming convention tools in Golang
How to Improve the Performance of Your Golang Application?
Golang HTML parser
How to access a struct from an external package in Go?
Example of Abstraction using Interfaces in Golang
Dynamic XML parser without Struct in Go
Example of Golang CRUD using MySQL from scratch