dou8mwz5079 2015-12-21 11:52
浏览 327
已采纳

使用sync.WaitGroup.wait时如何实现超时?

I have come across a situation that i want to trace some goroutine to sync on a specific point, for example when all the urls are fetched. Then, we can put them all and show them in specific order.

I think this is the barrier comes in. It is in go with sync.WaitGroup. However, in real situation that we can not make sure that all the fetch operation will succeed in a short time. So, i want to introduce a timeout when wait for the fetch operations.

I am a newbie to Golang, so can someone give me some advice?


What i am looking for is like this:

   wg := &sync.WaigGroup{}
   select {
   case <-wg.Wait():
   // All done!
   case <-time.After(500 * time.Millisecond):
   // Hit timeout.
   }

I know Wait do not support Channel.

  • 写回答

4条回答 默认 最新

  • duanchen7703 2015-12-22 23:54
    关注

    If all you want is your neat select, you can easily convert blocking function to a channel by spawning a routine which calls a method and closes/sends on channel once done.

    done := make(chan struct{})
    go func() {
       wg.Wait()
       close(done)
    }()
    
    select {
    case <-done:
    // All done!
    case <-time.After(500 * time.Millisecond):
    // Hit timeout.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大