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

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

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 &quot;fmt&quot;
import &quot;time&quot;


func main() {
  ch := make(chan string)
  go func() {
    for i:=0;i&lt;10;i++ {
      time.Sleep(time.Second * 1)
      ch &lt;- &quot;result&quot;
    }
      
  }()
  for {
    select {
    case res := &lt;-ch:
        fmt.Println(res)
    case &lt;-time.After(time.Second * 3):
        fmt.Println(&quot;timeout&quot;)
        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 := &lt;-ch:
			fmt.Println(res)
		case &lt;-timeoutChan:
			fmt.Println(&quot;timeout&quot;)
			return
		}
	}

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:

确定