为什么所有的goroutines都在睡觉——与ticker陷入僵局



我已经执行了一段时间,但仍然不明白为什么会出现死锁(https://play.golang.org/p/INeUl_ktMJA):

package main
import (
"context"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
t := time.NewTicker(time.Second)
for range t.C {
select {
case <-ctx.Done():
t.Stop()
default:
print(".")
}
}
cancel()
}

我希望关闭的上下文关闭应该退出范围循环的ticker通道,从而清理上下文。相反:

...fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/Users/andig/htdocs/test.go:12 +0xaf
exit status 2

它是在Stop((的文档中编写的:

Stop不会关闭通道,以防止从通道读取的并行goroutine看到错误的"tick"。

最新更新