Skip to content

Instantly share code, notes, and snippets.

@aichaoxy
Forked from metafeather/main.go
Last active November 13, 2023 03:31
Show Gist options
  • Save aichaoxy/a08b4507bf915b54c2663e9ad0ff49fb to your computer and use it in GitHub Desktop.
Save aichaoxy/a08b4507bf915b54c2663e9ad0ff49fb to your computer and use it in GitHub Desktop.
Get goroutine id for debugging
package main
// 80195: doc/faq: explain why goroutines are anonymous | https://go-review.googlesource.com/c/go/+/80195
// faq: document why there is no way to get a goroutine ID | https://github.com/golang/go/issues/22770
import (
"fmt"
"runtime"
"strconv"
"strings"
"sync"
)
func goid() int {
var buf [64]byte
n := runtime.Stack(buf[:], false)
idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
id, err := strconv.Atoi(idField)
if err != nil {
panic(fmt.Sprintf("cannot get goroutine id: %v", err))
}
return id
}
func main() {
fmt.Println("main", goid())
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
i := i
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println(i, goid())
}()
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment