Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Wait for all Go routines to finish execution in Golang

Posted on February 25, 2020February 25, 2020 by admin

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

  • Add method to set the number of goroutines to wait for.
  • Done method which is called by each of the goroutines when finished.
  • Wait method which is used to block till all goroutines have finished and have called the Done method

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
  • go
  • goroutines
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme