Welcome To Golang By Example

Wait for all Go routines to finish execution in Golang

sync package of golang provides WaitGroup struct which can be used to wait for collection of goroutines to finish execution. The WaitGroup provides:

Let’s see a working code

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup
    wg.Add(2)
 
    go sleep(&wg, time.Second*1)
    go sleep(&wg, time.Second*2)
 
    wg.Wait()
    fmt.Println("All goroutines finished")
}

func sleep(wg *sync.WaitGroup, t time.Duration) {
    defer wg.Done()
    time.Sleep(t)
    fmt.Println("Finished Execution")
}

Output:

Finished Execution
Finished Execution
All goroutines finished