6

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 Answer 1

12

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.