我尝试执行 Timeout pattern为我的项目。这是上面链接的示例代码:
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 秒超时。在每次迭代中都有一个 2 secs 超时,因此它永远不会被执行。
在第二种情况下,由于计时器在循环之外,它不会在每次迭代中重新初始化,所以在 2 秒 之后,select 语句将捕获该信号并执行超时。
如果你想在每次迭代中等待 2 秒,那么你可以这样做
for {
select {
case ev := <-c.EventChannel():
// do something here
default:
// do nothing as non-blocking channel pattern
}
time.Sleep(2 *time.Second)
关于Golang channel : timeout pattern not work as example,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54386775/