Golang ProgramsGolang Programs

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.


// GO language program with an example of  WaitGroup to delay execution
// of the main function until after all goroutines are complete.

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()
}


C:\golang>go run example30.go
Japan
India
China
India
Japan
China
Japan
India
China
India
Japan
China
Japan

India

China


C:\golang>
WaitGroup is a counting semaphore that can be used to maintain a record of running goroutines. When the value of a WaitGroup is greater than zero, the Wait method will block. We declared a WaitGroup struct named groupTest and then groupTest.Add(3) we set the value of the WaitGroup to 3, noting three running goroutines. To decrement the value of the WaitGroup and eventually release the main function, calls to the Done method is called.

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.