Skip to content

WaitGroup example in Go

Simple example

func main() {
    var wg sync.WaitGroup
    wg.Add(3)

    go func(){
        defer wg.Done()
        doThing1()
    }()

    go func(){
        defer wg.Done()
        doThing2()
    }()

    go func(){
        defer wg.Done()
        doThing3()
    }()

    wg.Wait()
}

Real world example

func processAndGather(in <-chan int, processor func(int) int, num int) []int {
    out := make(chan int, num)
    var wg sync.WaitGroup
    wg.Add(num)
    for i := 0; i < num; i++ {
        go func() {
            defer wg.Done()
            for v := range in {
                out <- processor(v)
            }
        }()
    }
    go func() {
        wg.Wait()
        close(out)
    }()
    var result []int
    for v := range out {
        result = append(result, v)
    }
    return result
}

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback: dig +short txt issue.imzye.com
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No privacy information is collected here
Buy Me a Coffee