当前位置: > > > > 为什么所有的 goroutine 都在睡觉——与股票代码发生死锁?
来源:stackoverflow
2024-04-29 18:36:30
0浏览
收藏
来到的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《为什么所有的 goroutine 都在睡觉——与股票代码发生死锁?》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!
问题内容
我已经使用了一段时间,但仍然无法弄清楚为什么会出现僵局(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() }
我希望关闭的上下文能够关闭股票通道,该通道应该退出范围循环,从而清理上下文。相反:
...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”。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《为什么所有的 goroutine 都在睡觉——与股票代码发生死锁?》文章吧,也可关注公众号了解相关技术文章。