Go语言中的僵尸goroutine

huangapple go评论76阅读模式
英文:

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 {},没有breakreturn语句),并且不再执行有用的工作,那么它基本上就是一个内存泄漏;它永远不会被终止,只会占用资源,直到程序结束。

更多详情,请阅读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 breaks or returns) 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

huangapple
  • 本文由 发表于 2014年5月25日 19:44:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/23854900.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定