从go超时模式中学习并发模式,我尝试检查一个通道并打破for循环

1
2
3
4
5
6
7
8
9
10
11
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毫秒(每个时间延迟不准确性问题),这会大大降低for循环的速度。

骇人听闻的解决方案是让另一个goroutine(我知道它很便宜)来监听exitMessage

1
2
3
4
5
6
7
8
9
10
11
12
13
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


 }

有没有更好的模式可以中断for循环?


如何将select语句与默认子句一起使用,如果无法接收通道,将执行该默认子句?

1
2
3
4
5
6
7
8
9
10
11
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
       }
   }