卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34044本站已运行391

Go常见问题解答说“没有goroutine ID”,但我们可以从runtime.Stack中获取它。它是什么?

go常见问题解答说“没有goroutine id”,但我们可以从runtime.stack中获取它。它是什么?

问题内容

go faq 回答了“为什么没有 goroutine id?”的问题


goroutines do not have names; they are just anonymous workers. they expose no unique identifier, name, or data structure to the programmer.
https://go.dev/doc/faq#no_goroutine_id

我不相信“它们没有暴露唯一标识符”的解释,因为看起来我们可以通过使用runtime.stack()来获取goroutine id。

问题

  1. go faq 答案中的“唯一标识符”和runtime.stack提取的goroutine id有什么区别?

  2. 为什么 go faq 回答“他们没有公开唯一标识符”?

我想清楚地理解“为什么没有goroutine id?”回答!

runtime.stack() 似乎提供了 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]))
}

而且,还有另一种方法通过 ebpf 获取 goroutine id。

如何使用ebpf获取goroutine id


正确答案


Go常见问题解答中的“唯一标识符”和runtime.Stack提取的goroutine id有什么区别?

常见问题解答指出,goroutines 不会向程序员公开唯一的标识符、名称或数据结构。

运行时确实需要一种方法来识别 Goroutine,但没有支持的方法来获取该标识符。

Go文档没有指定runtime.Stack返回的堆栈跟踪的格式或goroutine编号的含义。问题中的代码现在可能会检索唯一的 id,但不能保证该代码将来也会这样做。

卓越飞翔博客
上一篇: 使用 CreateProcessAsUserW() 从服务启动时,Windows 计算器应用程序会因 WerFault 不一致而崩溃
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏