如何获取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实现

相关推荐
顾林海9 分钟前
探秘Android JVM TI:虚拟机背后的"隐形管家"
android·面试·性能优化
山东小木14 分钟前
JBoltAI需求分析大师:基于SpringBoot的大模型智能需求文档生成解决方案
人工智能·spring boot·后端·需求分析·jboltai·javaai·aigs
Moonbit25 分钟前
MoonBit 再次走进清华:张宏波受邀参加「思源计划」与「程序设计训练课」
前端·后端·编程语言
RestCloud28 分钟前
一站式数据集成:iPaaS 如何让开发者和业务人员都满意?
前端·后端·架构
稻草猫.1 小时前
Java多线程(一)
java·后端·java-ee·idea
Java中文社群1 小时前
炸裂:SpringAI新版发布,终于支持断线重连了!
java·后端·ai编程
秃顶老男孩.1 小时前
异步处理(前端面试)
前端·面试·职场和发展
哈喽姥爷1 小时前
Spring Boot--Bean的扫描和注册
java·spring boot·后端·bean的扫描和注册
problc1 小时前
Spring Boot `@Service` 互相调用全攻略:`@Autowired` vs `@Resource`
java·spring boot·后端
文心快码BaiduComate2 小时前
文心快码3.5S全新升级,体验多智能体协同开发,最高赢无人机!
前端·后端·程序员