How to get the number of goroutines associated with a WaitGroup?

9.2k Views Asked by At

Let’s say I use a WaitGroup to make the main thread of an application wait until all the goroutines I have launched from said main have completed.

Is there a safe, straightforward, way to assess at any point in time how many goroutines associated with said WaitGroup are still running?

2

There are 2 best solutions below

4
Volker On

Is there a safe, straightforward, way to assess at any point in time how many goroutines associated with said waitgroup are still running?

No, there isn't.

Simply because Go (the language) has no notion of "goroutines associated with [a] waitgroup".

1
blackgreen On

The internal state of the WaitGroup is not exposed, and it won't be: https://github.com/golang/go/issues/7202

I don't think we're likely to make this API more complex. I don't see any way to use counter and waiters that is not subject to race conditions, other than simply printing them out. And for that you can maintain your own counts.

You could implement a counter yourself:

type WaitGroupCount struct {
    sync.WaitGroup
    count int64
}

func (wg *WaitGroupCount) Add(delta int) {
    atomic.AddInt64(&wg.count, int64(delta))
    wg.WaitGroup.Add(delta)
}

func (wg *WaitGroupCount) Done() {
    atomic.AddInt64(&wg.count, -1)
    wg.WaitGroup.Done()
}

func (wg *WaitGroupCount) GetCount() int {
    return int(atomic.LoadInt64(&wg.count))
}

// Wait() promoted from the embedded field

However, even if the counter access is synchronized, it will become stale immediately after you read it, since other goroutines may go on and call Add or Done irrespective of what you are doing with the count — unless you synchronize the entire operation that depends on the count. But in that case, you might need a more complex data structure altogether.