Created
April 27, 2017 13:06
-
-
Save metafeather/3615b23097836bc36579100dac376906 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
# 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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just a side note. I think the original came from this thread: https://groups.google.com/g/golang-nuts/c/Nt0hVV_nqHE/m/bwndAYvxAAAJ