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

时间:2014-02-11 16:45:16

标签: go

从超时模式go concurrency patterns学习,我尝试检查一个频道并打破for循环

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):
       }
   }  

超时可以避免select从频道读取卡住。问题是在Windows XP机器上,该延迟远远超过1毫秒(每time delay inaccuracy problem),这显着减慢了for循环。

一个被黑客攻击的解决方案是让另一个goroutine(我知道它很便宜)来监听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


 }

是否有更好的模式可以在go中断for循环?

1 个答案:

答案 0 :(得分:11)

如果使用带有默认子句的select statement怎么样,如果频道无法接收,该子句会执行?

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
       }
   }