Go Routine Blocking Others: A Deeper Explanation
In Go, the following code exhibits an unusual behavior where a goroutine with an infinite loop seemingly prevents another goroutine's message from reaching the intended channel:
func main() { timeout := make(chan int) go func() { time.Sleep(time.Second) timeout <- 1 }() res := make(chan int) go func() { for { } res <- 1 }() select { case <-timeout: fmt.Println("timeout") case <-res: fmt.Println("res") } }
Instead of terminating after one second, the program enters an infinite loop. Why does this happen?
Understanding Cooperative Scheduling in Go
The answer lies in Go's use of cooperative scheduling for goroutines. Goroutines yield control to the scheduler under certain conditions, including:
Since the infinite loop in the first goroutine never yields, it prevents other goroutines from running and sending messages to channels. This includes the timeout channel, which is waiting for a message that will never arrive.
Potential Solutions
Although cooperative scheduling can lead to such situations, there are potential solutions:
The above is the detailed content of Why Does an Infinite Go Routine Block Other Goroutines from Sending to Channels?. For more information, please follow other related articles on the PHP Chinese website!