duang8642 2015-12-29 18:59 采纳率: 0%
浏览 26

如何等待一组goroutines? [重复]

This question already has an answer here:

let's say I want to start a group of goroutines and than wait for all of them to finish (e.g. return). I can think of some channel-based solution (e.g. create a channel and listen to it counting received messages which shall be sent by each of goroutines and quiting after receive corresponding number of msgs) but maybe there's a more elegant/efficient solution because this case seems very common.

</div>
  • 写回答

1条回答 默认 最新

  • dsaf415212 2015-12-29 19:19
    关注

    Yes; you want a *sync.WaitGroup, which you can use by calling waitGroup.Add(1) before starting each task, waitGroup.Done() when it finishes, and waitGroup.Wait() once you have started everything and want to wait for it all to finish, like this:

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    func main() {
        wg := new(sync.WaitGroup)
        for i := 1; i < 3; i++ {
            wg.Add(1)
            go func(i int) { // ensures each run gets distinct i
                fmt.Println("Sleeping", i, "seconds")
                time.Sleep(time.Duration(i) * time.Second)
                fmt.Println("Slept", i, "seconds")
                wg.Done()
            }(i)
        }
        wg.Wait()
        fmt.Println("All done")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么