Skip to content

Instantly share code, notes, and snippets.

@afriza
Forked from metafeather/main.go
Last active February 22, 2023 05:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afriza/22d096b9cdec2a4b2d2d03ab6b9a6c32 to your computer and use it in GitHub Desktop.
Save afriza/22d096b9cdec2a4b2d2d03ab6b9a6c32 to your computer and use it in GitHub Desktop.
Get goroutine id for debugging
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