英文:
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 < 10; i++ {
go func() {
done <- true
}()
}
<-done
instead of this
done := make(chan bool)
for i := 0; i < 10; i++ {
go func() {
done <- true
}()
}
for i := 0; i < 10; i++ {
<-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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论