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 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?