Search code examples
goconcurrencyruntimerunnablegoroutine

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: https://golang.org/doc/diagnostics.html 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?


Solution

  • 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: https://play.golang.org/p/6gi26PF3iTT

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