我尝试为我的项目实现超时模式。这是上面链接的示例代码:
c1 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c1 <- "result 1"
}()
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
另一个例子是:
c2 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c2 <- "result 2"
}()
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
}
我可以成功运行此示例。然后我尝试将其应用于我的项目。这是我的项目代码:
for {
select {
case ev := <-c.EventChannel():
// do something here
case <-time.After(2 * time.Second):
// this condition never happend
return
default:
// do nothing as non-blocking channel pattern
}
}
但我不知道为什么代码永远不会遇到超时情况。当我time.After(2 * time.Second)
移动到单独的语句中时,它可以工作。这是修改后的代码:
timeout := time.After(2 * time.Second)
for {
select {
case ev := <-c.EventChannel():
// do something here
case <-timeout:
require.Equal(t, "time out after 2s", "")
default:
// do nothing as non-blocking channel pattern
}
}
我不知道两种情况之间的区别。以及为什么第一个例子有效。请帮我弄清楚。
谢谢
基本上,如果有默认情况,select 语句不会等待,所以在您的情况下,它只是检查EventChannel
并进入默认情况,因为它没有阻塞并且不会等待2 seconds timeout
。在每次迭代中都有一个2 secs
超时,所以它永远不会被执行。
第二种情况下,由于计时器在循环之外,它不会在每次迭代中重新初始化2 seconds
因此在 select 语句之后将捕获该信号并执行超时。
如果你想在每次迭代中等待2 secs
,那么你可以做这样的事情
for {
select {
case ev := <-c.EventChannel():
// do something here
default:
// do nothing as non-blocking channel pattern
}
time.Sleep(2 *time.Second)
}