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条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历