go - Why doesn't this Golang code to select among multiple time.After channels work? -
why doesn't golang code select among multiple time.after channels work?
see code below. 'timeout' message never issued. why?
package main import ( "fmt" "time" ) func main() { count := 0 { select { case <-time.after(1 * time.second): count++ fmt.printf("tick %d\n", count) if count >= 5 { fmt.printf("ugh\n") return } case <-time.after(3 * time.second): fmt.printf("timeout\n") return } } }
run on playground: http://play.golang.org/p/1gku-cwvah
output:
tick 1 tick 2 tick 3 tick 4 tick 5 ugh
because time.after
function, on every iteration returns new channel. if want channel same iterations, should save before loop:
timeout := time.after(3 * time.second) { select { //... case <-timeout: fmt.printf("timeout\n") return } }
playground: http://play.golang.org/p/muwlgtxpnf.
Comments
Post a Comment