In the provided code, a timeout case is implemented using a select statement and a time.After() call. However, the timeout case is not getting executed.
The reason for this is that the time.After() function creates a new channel each time it is called. When the select statement receives a value from the c1 channel (in the first for loop), the existing time.After() channel is discarded. Thus, the timeout case never has an opportunity to receive a value.
To resolve this issue, create the time.After() channel only once, outside of the for loop. This ensures that the same channel is used for the timeout case throughout the execution.
Here's the modified code:
func main() { c1 := make(chan int, 1) go func() { for { time.Sleep(1500 * time.Millisecond) c1 <- 10 } }() timeout := time.After(2000 * time.Millisecond) for { select { case i := <-c1: fmt.Println(i) case <-timeout: fmt.Println("TIMEOUT") } } fmt.Scanln() }
With this modification, the timeout case will be executed successfully after 2 seconds, as long as no value is received from the c1 channel within that time frame.
The above is the detailed content of Why Doesn't My Golang Timeout Case Trigger When Using Channels?. For more information, please follow other related articles on the PHP Chinese website!