gpt4 book ai didi

go - 随着时间的推移而超时。After 并不像使用自动收报机或计时器超时

转载 作者:IT王子 更新时间:2023-10-29 02:33:52 25 4
gpt4 key购买 nike

我希望以下函数的行为方式相同

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com