Search code examples
concurrencygochannelcoroutinegoroutine

Wait for the termination of n goroutines


I need to start a huge amount of goroutines and wait for their termination. The intuitive way seems to use a channel to wait till all of them are finished :

package main

type Object struct {
    //data
}

func (obj *Object) Update(channel chan int) {
    //update data
    channel <- 1
    return
}

func main() {

    channel := make(chan int, n)
    list := make([]Object, n, m)
    for {
        for _, object := range list {
            go object.Update(channel)
        }
        for i := 0; i < n; i++ {
            <-channel
        }
        //now everything has been updated. start again
    }
}

But the problem is that the amount of objects and therefore the amount of goroutines could change. Is it possible to change the buffer size of a channel ?

Is there maybe a more elegant way to do this ?


Solution

  • I've used WaitGroup as a solution to this problem. Translating your current code, with some logs to make it clear what's happening:

    package main
    
    import "sync"
    import "fmt"
    import "time"
    
    type Object struct {
        //data
    }
    
    func (obj *Object) Update(wg *sync.WaitGroup) {
        //update data
        time.Sleep(time.Second)
        fmt.Println("Update done")
        wg.Done()
        return
    }
    
    func main() {
        var wg sync.WaitGroup
        list := make([]Object, 5)
        for {
            for _, object := range list {
                wg.Add(1)
                go object.Update(&wg)
            }
            //now everything has been updated. start again
            wg.Wait()
            fmt.Println("Group done")
        }
    }