Golang timeout not running on channels

I am using goroutines / channels. Here is my code. Why is the timeout not running?

func main() { c1 := make(chan int, 1) go func() { for { time.Sleep(1500 * time.Millisecond) c1 <- 10 } }() go func() { for { select { case i := <-c1: fmt.Println(i) case <-time.After(2000 * time.Millisecond): fmt.Println("TIMEOUT") // <-- Not Executed } } }() fmt.Scanln() } 
+2
source share
1 answer

Your timeout will not happen, because one of your goroutine sends a value to your c1 channel every 1.5 seconds (or so), and your timeout will only happen if there is no value that will be received from c1 in within 2 seconds.

As soon as the value is obtained from c1 , in the next iteration that executes select , the new time.After() call will be called again, which returns a new channel through which the value will be sent only after 2 seconds. The timeout channel from the previous select execution is discarded and is no longer used.

To get a timeout after 2 seconds, create a timeout channel only once, for example:

 timeout := time.After(2000 * time.Millisecond) for { select { case i := <-c1: fmt.Println(i) case <-timeout: fmt.Println("TIMEOUT") // Will get executed after 2 sec } } 

Output:

 10 TIMEOUT 10 10 10 ... 
+2
source

All Articles