为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

哈士奇WWW 2022-09-19 21:30:04
我有一个类似于以下程序的程序:package mainimport (    "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
查看完整描述

1 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

如果使用上下文而不是计时器,则仅在退出函数大小写条件时调用取消。


package main


import (

    "context"

    "fmt"

    "time"

)


func main() {

    ch := make(chan string)

    go endProgram(ch)

    printFunc(ch)

}


func printFunc(ch chan string) {

    for {

        ctx, cancel := context.WithTimeout(context.Background(), getTimeoutDuration())

        select {

        case s := <-ch:

            cancel()

            fmt.Println(s)

            return

        case <-ctx.Done():

            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

}


查看完整回答
反对 回复 2022-09-19
  • 1 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号