php editor Xiaoxin may encounter situations where it does not work when using the custom "timeout waiting channel". This may be due to some common issues, such as incorrect configuration or coding issues. In order to make the custom "timeout waiting for channel" work, there are some workarounds we can take. First, we need to make sure that the channel and timeout are configured correctly. Secondly, we can check if there are any bugs or logic issues in the code that might cause the timeout to wait for the channel not to work. Finally, we can also consider using other related technologies or tools to deal with timeout waiting problems, such as using packaging libraries or using timers to monitor and handle timeout situations. Through these methods, we can make the custom "timeout waiting channel" work properly and improve the performance and stability of our application.
I'm trying to make my own custom "channel timeout". More precisely, it is the time.after
function. In other words, I'm trying to implement this:
select { case v := <-c: fmt.println("value v: ", v) case <-time.after(1 * time.second): fmt.println("timeout") }
But unfortunately I ran into a problem.
My implementation is:
func waitFun(wait int) chan int { time.Sleep(time.Duration(wait) * time.Second) c := make(chan int) c <- wait return c } func main() { c := make(chan int) go func() { time.Sleep(3 * time.Second) c <- 10 }() select { case v := <-c: fmt.Println("Value v: ", v) case <-waitFun(1): fmt.Println("Timeout") } time.Sleep(4 * time.Second) }
For some reason this doesn't work. The error is: all goroutines are sleeping - deadlock!
. I know that at some point all goroutines (main and those introduced with anonymous functions) go to sleep, but is this the reason for the bug or something else? I mean, it's not "infinite sleep" or "infinite wait for something", so it's not a deadlock, right? Also, using time.after
will also make the goroutine sleep, right? What do I need to change to make my program work?
select
statement will evaluate all cases at runtime, so this code will actually wait for waitfun
to return before starting to detect Listen to any channel. You must change waitfun
to return the channel immediately:
func waitFun(wait int) chan int { c := make(chan int) go func() { time.Sleep(time.Duration(wait) * time.Second) c <- wait }() return c }
The above is the detailed content of Why doesn't my custom 'Timeout Wait Channel' work and how do I make it work?. For more information, please follow other related articles on the PHP Chinese website!