如何获取go协程的ID?

协程G 底层实现

go 复制代码
type g struct {
	// Stack parameters.
	stack       stack   // offset known to runtime/cgo
	stackguard0 uintptr // offset known to liblink
	stackguard1 uintptr // offset known to liblink

	_panic    *_panic // innermost panic - offset known to liblink
	_defer    *_defer // innermost defer
	m         *m      // current m; offset known to arm liblink
	sched     gobuf
	syscallsp uintptr // if status==Gsyscall, syscallsp = sched.sp to use during gc
	syscallpc uintptr // if status==Gsyscall, syscallpc = sched.pc to use during gc
	syscallbp uintptr // if status==Gsyscall, syscallbp = sched.bp to use in fpTraceback
	stktopsp  uintptr // expected sp at top of stack, to check in traceback
	param        unsafe.Pointer
	atomicstatus atomic.Uint32
	stackLock    uint32 // sigprof/scang lock; TODO: fold in to atomicstatus
	goid         uint64
   // ... 其他参数

获取go协程的ID

  1. 获取当前运行的G getg()
go 复制代码
// getg returns the pointer to the current g.
// The compiler rewrites calls to this function into instructions
// that fetch the g directly (from TLS or from the dedicated register).
func getg() *g
  1. 根据goid字段的偏移量 得到ID
go 复制代码
goidOffset := xxxx
// GoID returns the goroutine id of current goroutine
func GoID() int64 {
	g := getg()
	p_goid := (*int64)(unsafe.Pointer(g + goidOffset))
	return *p_goid
}

//go:linkname getg runtime.getg
func getg() uintptr

不同版本的go实现 goid字段的偏移可能不同 可以使用开源库获取 runtime路径下g结构体 然后获取goid的偏移量

go 复制代码
// github.com/modern-go/reflect2/type_map.go

// offset for go1.4
var goidOffset uintptr = 128

func init() {
        // TypeByName return the type by its name, just like Class.forName in java
	gType := reflect2.TypeByName("runtime.g").(reflect2.StructType)
	if gType == nil {
		panic("failed to get runtime.g type")
	}
	goidField := gType.FieldByName("goid")
	goidOffset = goidField.Offset()
}

获取go协程的ID有啥用?

可以实现 Goroutine-Local-Storage cloudwego/localsession实现

相关推荐
MacroZheng25 分钟前
IDEA官方中文文档正式发布,太全了!
java·后端·intellij idea
fashia32 分钟前
Java转Go日记(五十七):gin 中间件
开发语言·后端·golang·go·gin
ak啊34 分钟前
深入浅出:计算机网络中的数据封装与解封装之旅
前端·后端
汪子熙44 分钟前
深入理解 // eslint-disable-next-line no-eval 注释的作用与应用
前端·javascript·面试
写bug写bug1 小时前
深入理解MySQL binlog
数据库·后端·mysql
Dignity_呱1 小时前
Vue性能优化:从加载提速到运行时优化
前端·vue.js·面试
这里有鱼汤1 小时前
AKShare被限IP、Tushare要积分?这才是最适合量化用的数据接口
后端·python
whltaoin1 小时前
Java面试专项一-准备篇
java·面试
天天摸鱼的java工程师2 小时前
凌晨四点,掘金签到 bug 现场抓包,开发同学速来认领!
服务器·前端·后端
SimonKing2 小时前
揭秘自定义注解,背后的面向切面编程(AOP)的艺术
java·后端·架构