我正在创建此功能以测试创建和停止计时器。运行时出现死锁错误:
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/