github.com/avicd/go-utilx@v0.1.0/goid/index.go (about) 1 package goid 2 3 import ( 4 "github.com/avicd/go-utilx/logx" 5 "reflect" 6 "unsafe" 7 ) 8 9 var gt reflect.Type 10 11 // return the pointer of runtime.g 12 func getgp() unsafe.Pointer 13 14 var goidOffset uintptr 15 16 func init() { 17 gt = typeByString("runtime.g") 18 if gt == nil { 19 logx.Fatal("Failed to get type of runtime.g natively.") 20 } 21 if tf, ok := gt.FieldByName("goid"); ok { 22 goidOffset = tf.Offset 23 } 24 } 25 26 func Id() int64 { 27 gp := getgp() 28 if gp == nil { 29 logx.Fatal("Failed to get gp from runtime natively.") 30 } 31 return *(*int64)(add(gp, goidOffset)) 32 } 33 34 // Should be a built-in for unsafe.Pointer? 35 // 36 //go:nosplit 37 func add(p unsafe.Pointer, x uintptr) unsafe.Pointer { 38 return unsafe.Pointer(uintptr(p) + x) 39 }