Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of specific go routines running

Tags:

go

In go's runtime lib we have NumGoroutine() to return the total number of go routines running at that time. I was wondering if there was a simple way of getting the number of go routines running of a specific function?

Currently I have it telling me I have 1000, or whatever, of all go routines but I would like to know I have 500 go routines running func Foo. Possible? Simple? Shouldn't bother with it?

like image 793
Jeff Avatar asked Mar 22 '23 20:03

Jeff


1 Answers

I'm afraid you have to count the goroutines on your own if you are interested in those numbers. The cheapest way to achieve your goal would be to use the sync/atomic package directly.

import "sync/atomic"

var counter int64

func example() {
    atomic.AddInt64(&counter, 1)
    defer atomic.AddInt64(&counter, -1)

    // ...
}

Use atomic.LoadInt64(&counter) whenever you want to read the current value of the counter.

And it's not uncommon to have a couple of such counters in your program, so that you can monitor it easily. For example, take a look at the CacheStats struct of the recently published groupcache source.

like image 53
tux21b Avatar answered Mar 25 '23 11:03

tux21b