Home >Backend Development >Golang >Why Doesn't My Go Goroutine Timeout Channel Ever Trigger?
Goroutine Timeout Channel Never Invoked
When using goroutines and channels in Go, it's essential to understand how timeouts work. In this code snippet, the goal is to print "TIMEOUT" after 2 seconds if no value is received on the channel c1. However, the timeout case is never executed.
Explanation:
The issue lies in the way the timeout channel is created inside the select loop. Each time a value is received from c1, a new timeout channel is created using time.After(...). This effectively cancels the previous timeout and starts a new one. As long as c1 continues to receive values, the timeout channel is constantly reset and never reaches its 2-second expiration.
Solution:
To ensure the timeout is triggered as intended, move the creation of the timeout channel outside the select loop. By creating it only once, the channel remains active until its expiration is reached, regardless of values received from c1.
Modified Code:
func main() { c1 := make(chan int, 1) timeout := time.After(2000 * time.Millisecond) go func() { for { time.Sleep(1500 * time.Millisecond) c1 <- 10 } }() for { select { case i := <-c1: fmt.Println(i) case <-timeout: fmt.Println("TIMEOUT") } } fmt.Scanln() }
Output:
10 10 10 ... TIMEOUT
Now, after 2 seconds of inactivity on c1, "TIMEOUT" is correctly printed.
The above is the detailed content of Why Doesn't My Go Goroutine Timeout Channel Ever Trigger?. For more information, please follow other related articles on the PHP Chinese website!