Continuing with our lockdown learning of Go language. Here’s a video on WaitGroup in goroutines in Golang
A goroutine may have to wait for another goroutine to complete. Using time.Sleep() is a very crude way to wait. Here’s where WaitGroup comes to picture. This is similar to CountDownLatch in Java
package main import ( "fmt" "math/rand" "sync" "time" ) func main() { //We need to ask main goroutine to wait for fixIssues() goroutine to complete its task wg := sync.WaitGroup{} wg.Add(1) //WaitGroup is like a countdown system. It will wait till the count is 1 go fixIssues(&wg) //time.Sleep(time.Second * 5)//Not intuitive and correct too //Main go routine is waiting now //Blocking statement wg.Wait() fmt.Println("***Enough! I am done waiting") } func fixIssues(wg *sync.WaitGroup) { defer wg.Done() //When the goroutine is completed, it sends a signal ie., it has completed for the lock to release i := 0 rand.Seed(time.Now().UnixNano()) iterations := rand.Intn(20) fmt.Println("Time required:", iterations, "seconds") for i < iterations { fmt.Println("Fixing Issues ...") time.Sleep(time.Second * 1) i++ } }
You can watch other videos in Go lang in the links below