6

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?

Gert Cuykens
  • 6,845
  • 13
  • 50
  • 84
  • `leak` always bindings to business(what your code want to do). If your program running well, leaving the routines, that's not `leak`. my opinion – Jiang YD Jan 26 '16 at 03:53
  • @JiangYD You are right I edited the question to be more precise. – Gert Cuykens Jan 26 '16 at 04:22
  • 1
    [`runtime.GoroutineProfile`](https://golang.org/pkg/runtime/#GoroutineProfile) has all the goroutines running and their stacktraces. Maybe better, [this answer describes using `runtime/pprof`](http://stackoverflow.com/questions/19094099/how-to-dump-goroutine-stacktraces) to get the whole traces printed. It's up to you then to figure out if the number of routines running is expected or not, of course. – twotwotwo Feb 04 '16 at 19:27

1 Answers1

4

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

David Budworth
  • 11,248
  • 1
  • 36
  • 45