du1068 2014-12-04 07:24
浏览 60
已采纳

使用goroutine进入WaitGroup

I wonder why we need to run the wg.Wait() in goroutine

// This one works as expected...
func main() {
    var wg sync.WaitGroup
    for i:=0; i<5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
        }()
        time.Sleep(time.Second)
    }
    go func() {
        wg.Wait()
    }()
}

But this one never ends waiting forever

func main() {
    var wg sync.WaitGroup
    for i:=0; i<5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
        }()
        time.Sleep(time.Second)
    }
    wg.Wait()
}

Can anybody explain why I need to wait in another goroutine?

Thanks!

  • 写回答

1条回答 默认 最新

  • doutang7383 2014-12-04 08:03
    关注

    why we need to run the wg.Wait() in goroutine?

    In the example you mention (coop/blob/master/coop.go#L85), the wait is in a goroutine in order to return immediately a channel that will indicate when all the other goroutines have completed. Those are the goroutines to be started:

    for _, fn := range fns {
        go func(f func()) {
            f()
            wg.Done()
        }(fn)
    }
    

    They mention the completion through the var wg sync.WaitGroup.
    That WaitGroup is set to wait for the right number of goroutines to finish:

    wg.Add(len(fns))
    

    The wait is done in a goroutine because it will in turn signal the global completion to a channel:

    go func() {
        wg.Wait()
        doneSig(ch, true)
    }()
    

    But the channel is returned immediately.

    ch := make(chan bool, 1)
    ...
    return ch
    

    That is why the Wait is done asynchronously: you don't want to wait in this function. You just want the channel.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题