英文:
it is quite common way to implement a timeout, why time.After is not working
问题
以下是翻译好的内容:
下面是Go代码,我尝试通过Go协程打印"result"。为什么在3秒后没有打印"timeout",而是在10秒后打印。因为所有的10个"result"都被打印了。
package main
import "fmt"
import "time"
func main() {
ch := make(chan string)
go func() {
for i:=0;i<10;i++ {
time.Sleep(time.Second * 1)
ch <- "result"
}
}()
for {
select {
case res := <-ch:
fmt.Println(res)
case <-time.After(time.Second * 3):
fmt.Println("timeout")
return
}
}
}
/**
result
result
result
result
result
result
result
result
result
result
timeout
*/
英文:
the go code is show below, i try to print "result" by go routine. why "timeout" is not print after 3 second, but 10 second.since all the 10 "result" print.
package main
import "fmt"
import "time"
func main() {
ch := make(chan string)
go func() {
for i:=0;i<10;i++ {
time.Sleep(time.Second * 1)
ch <- "result"
}
}()
for {
select {
case res := <-ch:
fmt.Println(res)
case <-time.After(time.Second * 3):
fmt.Println("timeout")
return
}
}
}
/**
result
result
result
result
result
result
result
result
result
result
timeout
*/
答案1
得分: 3
在每个for循环中,在case res := <-ch之后,你创建了一个新的channel <-time.After(time.Second * 3)。
这个修复可能是你想要的:
timeoutChan := time.After(time.Second * 3)
for {
select {
case res := <-ch:
fmt.Println(res)
case <-timeoutChan:
fmt.Println("timeout")
return
}
}
英文:
In each for loop, after case res := <-ch, you create a new channel <-time.After(time.Second * 3).
This fix maybe what you want:
timeoutChan := time.After(time.Second * 3)
for {
select {
case res := <-ch:
fmt.Println(res)
case <-timeoutChan:
fmt.Println("timeout")
return
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论