-
-
Save aichaoxy/a08b4507bf915b54c2663e9ad0ff49fb 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 | |
// 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