duanmao2650 2014-02-11 16:45
浏览 105
已采纳

golang使用带有超时模式的通道跳出循环

Learning from go time out pattern go concurrency patterns, I try to check a channel and to break out of a for loop

Loop: 
   for {
      //do something repeatedly very fast in the for loop

     //check exitMessage to see whether to break out or not
      select {
          case <- exitMessage:
               break Loop
          case <- time.After(1 * time.Millisecond):
       }
   }  

The time-out avoids select gets stuck reading from a channel. The problem is that on a Windows XP machine, that delay is much longer than 1 millisecond (per time delay inaccuracy problem) which slows down the for-loop significantly.

A hacked-up solution is to get another goroutine (I know it's cheap) to listen for the exitMessage

exitFlag := 0

//another goroutine to check exitMessage
go fun(in chan int){
    exitFlag = <-in
}(exitMessage)


for exitFlag == 0 {
       //do something repeatedly very fast in the for loop


 }

Is there a better pattern to interrupt a for-loop in go?

  • 写回答

1条回答 默认 最新

  • duanhuokuang5280 2014-02-11 16:54
    关注

    How about using a select statement with a default clause which will execute if the channel can't receive?

    Loop:
       for {
          select {
              //check exitMessage to see whether to break out or not
              case <- exitMessage:
                   break Loop
              //do something repeatedly very fast in the for loop
              default:
                   // stuff
           }
       }  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)