Skip to content

Instantly share code, notes, and snippets.

@metafeather
Created April 27, 2017 13:06
Show Gist options
  • Save metafeather/3615b23097836bc36579100dac376906 to your computer and use it in GitHub Desktop.
Save metafeather/3615b23097836bc36579100dac376906 to your computer and use it in GitHub Desktop.
Get goroutine id for debugging
# ref: https://play.golang.org/p/OeEmT_CXyO
package main
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()
}
@afriza
Copy link

afriza commented Feb 17, 2023

Just a side note. I think the original came from this thread: https://groups.google.com/g/golang-nuts/c/Nt0hVV_nqHE/m/bwndAYvxAAAJ

@vituchon
Copy link

Whoa thanks!! 🤓🦦👌🏿

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment