英文:
Does time.Sleep() yield to other goroutines?
问题
在Go语言中,调用time.Sleep()会让出给其他的goroutine吗?我有一种感觉它会,但在其他的答案中(例如:https://stackoverflow.com/questions/10095751/understanding-goroutines),time.Sleep并没有被明确列为调度点。
英文:
In Go, does a call to time.Sleep() yield to other goroutines? I have a feeling it does, but in other answers (eg: https://stackoverflow.com/questions/10095751/understanding-goroutines) time.Sleep is not explicitly listed as a scheduling point.
答案1
得分: 6
是的。请参阅调度器中的抢占。
在之前的版本中,一个无限循环的 goroutine 可能会使同一线程上的其他 goroutine 饿死,当 GOMAXPROCS 只提供一个用户线程时,这是一个严重的问题。在 Go 1.2 中,这个问题在一定程度上得到了解决:调度器在进入函数时会偶尔被调用。这意味着任何包含(非内联)函数调用的循环都可以被抢占,从而允许同一线程上的其他 goroutine 运行。
以下设计文档也是了解调度器更多信息的好资源:
英文:
Yes. See Pre-emption in the scheduler.
> In prior releases, a goroutine that was looping forever could starve out other goroutines on the same thread, a serious problem when GOMAXPROCS provided only one user thread. In Go 1.2, this is partially addressed: The scheduler is invoked occasionally upon entry to a function. This means that any loop that includes a (non-inlined) function call can be pre-empted, allowing other goroutines to run on the same thread.
Following design docs are also good reads to learn more about scheduler:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论