Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang use channel with time out pattern to jump out of loop

Tags:

go

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?

like image 824
Zhe Hu Avatar asked Feb 11 '14 16:02

Zhe Hu


Video Answer


1 Answers

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
       }
   }  
like image 92
Nick Craig-Wood Avatar answered Nov 15 '22 06:11

Nick Craig-Wood