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 (
    "fmt"
    "sync"
    "time"
)

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

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

    // Notify the WaitGroup that this worker is done.
    wg.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++ {
        wg.Add(1)
        go add(i, i + 1, &wg)
    }

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

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

View on github

Pre – Next