Search code examples
gogoroutine

Can an external program know the number of goroutine in the go program?


I can get the value through this "runtime.NumGoroutine()"..

Can I know the number of goroutines in an external program?


Solution

  • Maybe you can use delve.

    1. go get github.com/derekparker/delve/cmd/dlv
    2. run your main application
    3. find the $pid of your main applicaiton
    4. dlv attach $pid, then type goroutines to see all go routines like follows:
    C:\work\gowork>dlv attach 5696
    Type 'help' for list of commands.
    (dlv) goroutines
    [5 goroutines]
      Goroutine 1 - User: C:/devsoft/Go/src/runtime/time.go:102 time.Sleep (0x440c3b)
      Goroutine 2 - User: C:/devsoft/Go/src/runtime/proc.go:292 runtime.gopark (0x42a03f)
      Goroutine 3 - User: C:/devsoft/Go/src/runtime/proc.go:292 runtime.gopark (0x42a03f)
      Goroutine 17 - User: C:/devsoft/Go/src/runtime/proc.go:292 runtime.gopark (0x42a03f)
    * Goroutine 19 - User: :0 ??? (0x7fffef855427) (thread 15260)
    (dlv)
    

    Then, what your program needs to do is to control the command dlv using something like expect to control the debug tool to input goroutines command.

    Seems it has a xml-rpc like api for client to get more infomation, you may can have a look, I did not use the api before.

    Just a thought, FYI.