Golang获取goroutine ID

Posted by 聪少 on 2018-04-25

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

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!