英文:
Zombie goroutines in Go
问题
我一直在想,一个在Go语言中的goroutine是如何被终止的,直到最近我观看了John Graham-Cumming在GoPherCon上的*A Channel Compendium*演讲,才意识到这其实很简单,只需要在goroutine执行的代码中加入一个return语句即可。那闭包也是一样的吗?我们是否应该在闭包中始终使用return语句,以便每个执行闭包的goroutine都能在某个时刻终止?在系统中存在僵尸goroutine有什么缺点,它们是如何被终止的?
英文:
I was always wondering how could a goroutine in Go get killed until i recently watched A Channel Compendium by John Graham-Cumming at GoPherCon and realized that its as simple as having a return statement inside the code executed by goroutines. So the same goes for closures right? Shouldn't we always use return statements inside closures so every goroutine executing a closure terminates at some point? What are the disadvantages of having zombie goroutines in your system and how do they get terminated?
答案1
得分: 3
根据Jsor的评论,一个函数必须返回以结束一个goroutine,即使没有显式的return
语句,如果函数执行到末尾也会发生这种情况。
如果一个goroutine永远不返回(例如因为它包含一个无限循环for {}
,没有break
或return
语句),并且不再执行有用的工作,那么它基本上就是一个内存泄漏;它永远不会被终止,只会占用资源,直到程序结束。
更多详情,请阅读https://groups.google.com/forum/#!topic/golang-nuts/uiySuH8_3Y4中的讨论。
英文:
As per Jsor's comment, a function must return to end a goroutine, but that can happen if it reaches the end of the function even if there isn't an explicit return
statement.
If a goroutine never returns (for example because it contains an infinite for {}
with no break
s or return
s) and is no longer doing useful work then it is basically a memory leak; it will never get terminated, and it simply sits and chews up resources until your program ends.
For more details, read the thread at https://groups.google.com/forum/#!topic/golang-nuts/uiySuH8_3Y4
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论