Go: Get Goroutine ID

 

func GetGoroutineID() int {
    var buf = make([]byte, 128)
    b := runtime.Stack(buf, false)
    idField := strings.Fields(strings.TrimPrefix(string(buf[:b]), "goroutine "))[0]
    id, err := strconv.Atoi(idField)
    if err != nil {
        panic(fmt.Sprintf("cannot get goroutine id: %v", err))
    }
    return id
}

 

posted @ 2023-03-17 20:43  ascertain  阅读(20)  评论(0)    收藏  举报