停止时间。新计时器初始化在 for 循环内

我有一个类似于以下程序的程序:


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



哈士奇WWW
浏览 66回答 1
1回答

Smart猫小萌

如果使用上下文而不是计时器,则仅在退出函数大小写条件时调用取消。package mainimport (&nbsp; &nbsp; "context"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; ch := make(chan string)&nbsp; &nbsp; go endProgram(ch)&nbsp; &nbsp; printFunc(ch)}func printFunc(ch chan string) {&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; ctx, cancel := context.WithTimeout(context.Background(), getTimeoutDuration())&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case s := <-ch:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cancel()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(s)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Current value")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}func endProgram(ch chan string) {&nbsp; &nbsp; time.Sleep(time.Second * 8)&nbsp; &nbsp; ch <- "Exit function"}func getTimeoutDuration() time.Duration {&nbsp; &nbsp; return time.Second * 3}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python