Wait some goroutine to finish with waitgroup

(3 minutes for reading)

In case we have many goroutines are running. To wait for multiple goroutines to finish, we can use a wait group.

I declared 1 function add(a int, b int *sync.Waitgroup) to add a and b

In main function, we call go-routine for add func in 5 times. For each calling, we invoke waitgroup add 1 process

After that waitgroup.Wait() to wait all of them are done.

That mean, when you ws.Add(1), it count up process. And when ws.Wait(), it block until the WaitGroup count down and counter goes back to 0 (by .Done()); all the workers notified they’re done.

// To wait for multiple goroutines to finish, we can
// use a *wait group*.

package main

import (

func add(a int, b int, wg *sync.WaitGroup) {
    fmt.Println("Worker starting add", a, b)

    // Sleep to simulate an expensive task.
    fmt.Println("Worker done with result", a + b)

    // Notify the WaitGroup that this worker is done.

func main() {

    // This WaitGroup is used to wait for all the
    // goroutines launched here to finish.
    var wg sync.WaitGroup

    // Launch several goroutines and increment the WaitGroup
    // counter for each.
    for i := 1; i <= 5; i++ {
        go add(i, i + 1, &wg)

    // Block until the WaitGroup counter goes back to 0;
    // all the workers notified they're done.

    fmt.Println("We finish all add function")

View on github

Pre – Next