有没有一种工具可以检测我是否忘记关闭 goroutine?

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

Is there a tool to detect when I forget to close goroutines?

问题

当我这样做时:

done := make(chan bool)
for i := 0; i < 10; i++ {
	go func() {
		done <- true
	}()
}
<-done

而不是这样做:

done := make(chan bool)
for i := 0; i < 10; i++ {
	go func() {
		done <- true
	}()
}
for i := 0; i < 10; i++ {
	<-done
}

如果我不关闭goroutine,是否会造成goroutine泄漏?是否有工具可以检测我是否忘记关闭goroutine?

英文:

When I do this

done := make(chan bool)
for i := 0; i &lt; 10; i++ {
	go func() {
		done &lt;- true
	}()
}
&lt;-done

instead of this

done := make(chan bool)
for i := 0; i &lt; 10; i++ {
	go func() {
		done &lt;- true
	}()
}
for i := 0; i &lt; 10; i++ {
	&lt;-done
}

Am I leaking goroutines if I do not close them and Is there a tool to detect when I forget to close goroutines?

答案1

得分: 4

是的,你在第一个示例中泄漏了9个goroutine。

我不认为有任何工具可以告诉你这一点。

如果有一种方法可以查询所有现有的非系统(即:gc)goroutine,那将是一件有趣的事情。

可能可以使用runtime.Stack来做一些事情,但这将非常特定于给定的代码库,因为你可能有一些“好”的goroutine和一些“不良”的goroutine。

更新:2016年2月4日

我对此很好奇,所以我制作了一个非常简单(并且命名可怕)的库,用于对比不同时间的goroutine。一个简单的泄漏检测器。https://github.com/dbudworth/greak

英文:

Yes, you are leaking 9 goroutines in you first example.

I don't believe there's any tool to tell you this.

would be an interesting thing to make, if there's a way to query for all existing non-system (ie: gc) goroutines.

Probably can do something with: runtime.Stack, but it would be super-specific
to a given codebase as you likely have some "good" goroutines and some "rogue" ones.

Update: Feb 4, 2016

I got curious on this, so I made a really simple (and terribly named) library to do a diff of goroutines over time. A simplistic leak detector. https://github.com/dbudworth/greak

huangapple
  • 本文由 发表于 2016年1月26日 11:22:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/35006560.html
匿名

发表评论

匿名网友

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

确定