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

相关推荐
华仔啊5 分钟前
35岁程序员失业了,除了送外卖,还能做什么?
前端·后端·程序员
SimonKing17 分钟前
【开发者必备】Spring Boot 2.7.x:WebMvcConfigurer配置手册来了(二)!
java·后端·程序员
程序员飞哥23 分钟前
别再说“对接接口没技术含量了”,这才是高手的打开方式!
后端·程序员
DokiDoki之父28 分钟前
Spring—容器
java·后端·spring
摇滚侠40 分钟前
Spring Boot 3零基础教程,WEB 开发 国际化 Spring Boot + Thymeleaf 笔记45
spring boot·笔记·后端
间彧43 分钟前
Java AQS详解与项目实战
后端
golang学习记1 小时前
性能飙升4倍,苹果刚发布的M5给人看呆了
人工智能·后端
晨非辰1 小时前
【数据结构入坑指南】--《层序分明:堆的实现、排序与TOP-K问题一站式攻克(源码实战)》
c语言·开发语言·数据结构·算法·面试
Moment1 小时前
快手前端校招一面面经 🤔🤔🤔
前端·javascript·面试
程序员爱钓鱼1 小时前
Python编程实战 · 基础入门篇 | 类型转换与输入输出
后端·python