首頁  >  文章  >  後端開發  >  Go常見問題解答說“沒有goroutine ID”,但我們可以從runtime.Stack中取得它。它是什麼?

Go常見問題解答說“沒有goroutine ID”,但我們可以從runtime.Stack中取得它。它是什麼?

WBOY
WBOY轉載
2024-02-05 22:51:03549瀏覽

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,但不能保證該程式碼將來也會這樣做。

以上是Go常見問題解答說“沒有goroutine ID”,但我們可以從runtime.Stack中取得它。它是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除