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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With