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.

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

报告相同问题?

悬赏问题

  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信
  • ¥30 Python调用dll文件输出Nan重置dll状态
  • ¥15 浮动div的高度控制问题。
  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题