How to count the number of goroutine in runnable state


I am testing my Go application. Right now I’m getting some information, but I wanted to know how to know the exact number (given some time instant) of goroutines in the runnable state: the function NumGoroutine() of the runtime package returns the number of goroutines that currently exist (which are many more than those in the runnable state!).

This is my function which prints the goroutine number every second:

func count() {
    for {
        fmt.Println("Number of runnable goroutines: ", runtime.NumGoroutine())
        time.Sleep(1 * time.Second)

Unfortunately, the result is not good (the number of goroutines in the program is constantly growing, and I know that so many goroutines cannot be active at the same time!). This page: says that debug.Stack returns the current stack trace. Stack trace is useful to see how many goroutines are currently running, what they are doing, and whether they are blocked or not.

If I print debug.Stack() (instead of runtime.NumGoroutine()) the result changes completely (every second it always prints the same stack!). My question is: is len(debug.Stack()) the correct number of goroutines in the runnable state? It seems to me not, since this number is constant.
How do I get the right information?


I don’t recommend to use this way (because that’s how it works inside runtime and might be changed at future), but in testing purposes would be fine:

As you can see, running and runnable states are the different states.

Answered By – Laevus Dexter

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.