我有一个类似于以下程序的程序:
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan string)
go endProgram(ch)
printFunc(ch)
}
func printFunc(ch chan string) {
for {
timeout := time.NewTimer(getTimeoutDuration())
defer timeout.Stop()
select {
case s := <-ch:
fmt.Println(s)
return
case <-timeout.C:
fmt.Println("Current value")
}
}
}
func endProgram(ch chan string) {
time.Sleep(time.Second * 8)
ch <- "Exit function"
}
func getTimeoutDuration() time.Duration {
return time.Second * 3
}
在这种情况下,停止计时器的最佳方法是什么?timeout
我知道上面不是推荐的方法,因为使用for loop内部的延迟是一种不好的做法。另一种方法是在for循环中使用,而不是因为我们不必停止。但如果函数在计时器触发(源)之前退出,则会导致资源泄漏。time.Aftertime.NewTimertime.Aftertime.After
Smart猫小萌
相关分类