How do I inspect goroutine stacks?

In Go, you can inspect goroutine stacks to help with debugging and performance analysis. This is essential when you're dealing with concurrent programming, as it allows you to observe the state of each goroutine and understand what they are doing at any point in time.

To print the stack traces of all goroutines, the `runtime` package provides a function called `runtime.Stack`. You can call this function in your code to log the state of all goroutines.

package main import ( "fmt" "runtime" "time" ) func main() { go func() { time.Sleep(2 * time.Second) fmt.Println("Goroutine finished") }() // Allow the goroutine to start time.Sleep(1 * time.Second) // Print the stack of all goroutines buf := make([]byte, 1<<16) // buffer to hold stack traces stackSize := runtime.Stack(buf, true) fmt.Printf("Got %d bytes of stack\n", stackSize) fmt.Println(string(buf)) }

goroutine go lang debugging runtime package concurrent programming