Go FAQ answers the question, "Why is there no goroutine ID?"
Goroutines do not have names; they are just anonymous workers. They expose no unique identifier, name, or data structure to the programmer.
I am not convinced by the explanation "They expose no unique identifier" because it appears that we can get goroutine id by using runtime.Stack().
Question
What's the difference between "unique identifier" in Go FAQ answer and goroutine id extracted by runtime.Stack?
Why does Go FAQ answer "They expose no unique identifier"?
I want to clearly understand "Why is there no goroutine ID?" answer!
runtime.Stack() seems to provide goroutine id. https://go.dev/play/p/5b6FD7C8S6-
package main
import (
"bytes"
"errors"
"fmt"
"runtime"
"strconv"
)
func main() {
fmt.Println(goid())
done := make(chan struct{})
go func() {
fmt.Println(goid())
done <- struct{}{}
}()
go func() {
fmt.Println(goid())
done <- struct{}{}
}()
<-done
<-done
close(done)
}
var (
goroutinePrefix = []byte("goroutine ")
errBadStack = errors.New("invalid runtime.Stack output")
)
func goid() (int, error) {
buf := make([]byte, 32)
n := runtime.Stack(buf, false)
buf = buf[:n]
// goroutine 1 [running]: ...
buf, ok := bytes.CutPrefix(buf, goroutinePrefix)
if !ok {
return 0, errBadStack
}
i := bytes.IndexByte(buf, ' ')
if i < 0 {
return 0, errBadStack
}
return strconv.Atoi(string(buf[:i]))
}
And, there is another approach getting goroutine id by eBPF.