go - 为什么计时器停止会产生死锁错误?

标签 go

我正在创建此功能以测试创建和停止计时器。运行时出现死锁错误:

package main

import "fmt"
import "time"


func main() {
    livenessTimer := &time.Timer{}
    livenessInterval, _ := time.ParseDuration("1m")
    for {
        fmt.Print("Timer started")
        livenessTimer = time.NewTimer(livenessInterval)
        select {
        case <-livenessTimer.C:
            fmt.Print(time.Now())
            fmt.Println("timer triggered")
        }
        if !livenessTimer.Stop() {
            // drain timer from channel if any
            fmt.Println("drain timer")
            <-livenessTimer.C
        }
    }
}

当我运行此代码时,出现以下错误:
Timer started2009-11-10 23:01:00 +0000 UTC m=+60.000000001timer triggered
drain timer
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /tmp/sandbox748850751/prog.go:21 +0x2e0

Stop的文档建议检查返回值并耗尽 channel 。

最佳答案

这是文档中的关键部分:

...assuming the program has not received from t.C already



在您的情况下,计时器已启动,Stop返回false,您开始在没有其他goroutine运行的 channel 上等待,从而导致死锁。

关于go - 为什么计时器停止会产生死锁错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59975956/

相关文章:

for-loop - Golang 中的事件驱动模型

go - GO Lang 中的 HTTP POST 抛出错误

go - 在 go 中比较客户端证书

go - 如何将stdout的输出转换为golang中的字符串

go - 如何调用像“ZRem(key string, members ...string)”这样的 golang func?

mongodb - UpdateOne、ReplaceOne、FindOneAndReplace - 模式匹配,但没有更新数据

mysql - golang 在一周的特定日子(即每个星期五)采取行动

go - 没有任何 goroutine 但仍然得到 "all goroutines are asleep -deadlock"

go - cmd := exec. 命令 ("ssh", "ec2-user@publicip")退出权限被拒绝(公钥,gssapi-keyex,gssapi-with-mic)

go - 分析go程序时出现索引超出范围错误