dongxie5698 2013-05-16 14:53
浏览 68
已采纳

等待n个goroutine终止

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 ?

  • 写回答

3条回答 默认 最新

  • douyongdao4046 2013-05-16 15:10
    关注

    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")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?