-
-
Save afriza/22d096b9cdec2a4b2d2d03ab6b9a6c32 to your computer and use it in GitHub Desktop.
Get goroutine id for debugging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"runtime" | |
"strings" | |
"sync" | |
) | |
// Goid gets goroutine ID. Only used for debugging purpose. | |
// | |
// Refs: | |
// - https://groups.google.com/g/golang-nuts/c/Nt0hVV_nqHE/m/bwndAYvxAAAJ | |
// - https://play.golang.org/p/OeEmT_CXyO | |
// - https://gist.github.com/metafeather/3615b23097836bc36579100dac376906 | |
// - https://gist.github.com/afriza/22d096b9cdec2a4b2d2d03ab6b9a6c32 | |
func Goid() string { | |
var buf [64]byte | |
n := runtime.Stack(buf[:], false) | |
s := string(buf[:n]) | |
// Sample value for s: | |
// "goroutine 25 [running]:\nmain.Goid()\n\t/tmp/sandbox3231773321/prog" | |
s = strings.TrimPrefix(s, "goroutine ") | |
s, _, found := strings.Cut(s, " ") | |
if !found { // just in case, fallback to strings.Cut() + strings.Fields() | |
s, _, _ = strings.Cut(s, "\n") | |
s = strings.Fields(s)[0] | |
} | |
return s | |
} | |
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