作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我希望以下函数的行为方式相同
func fillChanTimeoutUsingTicker(maxDuration time.Duration, chanSize int) chan string {
c := make(chan string, chanSize)
ticker := time.NewTicker(maxDuration)
for {
select {
case <-ticker.C:
ticker.Stop()
fmt.Println("Ticker:operation timedout")
return c
case c <- "Random message":
default:
fmt.Println("Ticker:chan is full")
return c
}
}
}
func fillChanTimeoutUsingTimeAfter(maxDuration time.Duration, chanSize int) chan string {
c := make(chan string, chanSize)
for {
select {
case <-time.After(maxDuration):
fmt.Println("time.After:operation timedout")
return c
case c <- "Random message":
default:
fmt.Println("time.After:chan is full")
return c
}
}
}
称他们为:
resWithTicker := fillChanTimeoutUsingTicker(time.Duration(1*time.Microsecond), 10000000)
fmt.Println(len(resWithTicker))
resWithTimeAfter := fillChanTimeoutUsingTimeAfter(time.Duration(1*time.Microsecond), 10000000)
fmt.Println(len(resWithTimeAfter))
打印:
Ticker:operation timedout
43979
time.After:chan is full
10000000
我认为它们的行为方式完全相同,但我真的看不出有什么大的不同,对此有什么想法吗?
请注意,使用计时器也可以像在 ticker 函数中一样正常工作。
最佳答案
问题出在您的代码中。
在您的第一个示例中,您正在创建一个 自动收报机并将其用于超时。
在你的第二个例子中,你创建了一个计时器每次循环:
case <-time.After(maxDuration):
在library sources中可以看出, 这相当于
case <- time.NewTimer(maxDuration).C:
如果每次循环都创建一个新的 Ticker/Timer(并丢弃旧的),它可能永远不会触发。
因此,要让您的第二个示例正确运行,请这样做(未经测试):
func fillChanTimeoutUsingTimeAfter(maxDuration time.Duration, chanSize int) chan string {
c := make(chan string, chanSize)
t := time.After(maxDuration)
for {
select {
case <-t:
fmt.Println("time.After:operation timedout")
return c
case c <- "Random message":
default:
fmt.Println("time.After:chan is full")
return c
}
}
}
关于go - 随着时间的推移而超时。After 并不像使用自动收报机或计时器超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32668268/
我是一名优秀的程序员,十分优秀!