实现超时的常见方式是使用`time.After`,为什么它不起作用呢?

huangapple go评论113阅读模式
英文:

it is quite common way to implement a timeout, why time.After is not working

问题

以下是翻译好的内容:

下面是Go代码,我尝试通过Go协程打印"result"。为什么在3秒后没有打印"timeout",而是在10秒后打印。因为所有的10个"result"都被打印了。

  1. package main
  2. import "fmt"
  3. import "time"
  4. func main() {
  5. ch := make(chan string)
  6. go func() {
  7. for i:=0;i<10;i++ {
  8. time.Sleep(time.Second * 1)
  9. ch <- "result"
  10. }
  11. }()
  12. for {
  13. select {
  14. case res := <-ch:
  15. fmt.Println(res)
  16. case <-time.After(time.Second * 3):
  17. fmt.Println("timeout")
  18. return
  19. }
  20. }
  21. }
  22. /**
  23. result
  24. result
  25. result
  26. result
  27. result
  28. result
  29. result
  30. result
  31. result
  32. result
  33. timeout
  34. */
英文:

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.

  1. package main
  2. import &quot;fmt&quot;
  3. import &quot;time&quot;
  4. func main() {
  5. ch := make(chan string)
  6. go func() {
  7. for i:=0;i&lt;10;i++ {
  8. time.Sleep(time.Second * 1)
  9. ch &lt;- &quot;result&quot;
  10. }
  11. }()
  12. for {
  13. select {
  14. case res := &lt;-ch:
  15. fmt.Println(res)
  16. case &lt;-time.After(time.Second * 3):
  17. fmt.Println(&quot;timeout&quot;)
  18. return
  19. }
  20. }
  21. }
  22. /**
  23. result
  24. result
  25. result
  26. result
  27. result
  28. result
  29. result
  30. result
  31. result
  32. result
  33. timeout
  34. */

答案1

得分: 3

在每个for循环中,在case res := <-ch之后,你创建了一个新的channel <-time.After(time.Second * 3)。

这个修复可能是你想要的:

  1. timeoutChan := time.After(time.Second * 3)
  2. for {
  3. select {
  4. case res := <-ch:
  5. fmt.Println(res)
  6. case <-timeoutChan:
  7. fmt.Println("timeout")
  8. return
  9. }
  10. }
英文:

In each for loop, after case res := <-ch, you create a new channel <-time.After(time.Second * 3).

This fix maybe what you want:

  1. timeoutChan := time.After(time.Second * 3)
  2. for {
  3. select {
  4. case res := &lt;-ch:
  5. fmt.Println(res)
  6. case &lt;-timeoutChan:
  7. fmt.Println(&quot;timeout&quot;)
  8. return
  9. }
  10. }

huangapple
  • 本文由 发表于 2023年6月5日 15:35:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76404356.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定