Golang获取goroutine ID

Wed Apr 25, 2018

200 Words|Read in about 1 Min
Tags: golang  

golang本身不提供获取goroutineID的接口,如果要获取goroutineID可以使用下面的方法


package main

import (
    "bytes"
    "fmt"
    "runtime"
    "strconv"
)

func main() {
    fmt.Println(getGID())
}

func getGID() uint64 {
    b := make([]byte, 64)
    b = b[:runtime.Stack(b, false)]
    b = bytes.TrimPrefix(b, []byte("goroutine "))
    b = b[:bytes.IndexByte(b, ' ')]
    n, _ := strconv.ParseUint(string(b), 10, 64)
    return n
}

OK! See you!

See Also

Wed Apr 25, 2018

200 Words|Read in about 1 Min
Tags: golang