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

相关推荐
Java水解几秒前
MyBatis 源码深度解析:从 Spring Boot 实战到底层原理
后端·mybatis
随风飘的云43 分钟前
es搜索引擎的持久化机制原理
后端
Se7en25811 小时前
基于 MateChat 构建 AI 编程智能助手的落地实践
后端
n***F8751 小时前
Skywalking介绍,Skywalking 9.4 安装,SpringBoot集成Skywalking
spring boot·后端·skywalking
w***37512 小时前
SpringBoot【实用篇】- 测试
java·spring boot·后端
9ilk2 小时前
【C++】 --- 哈希
c++·后端·算法·哈希算法
MC丶科2 小时前
Spring Boot + Elasticsearch 实现全文搜索功能(商品搜索)!让搜索快如闪电
spring boot·后端·elasticsearch·软考高级·软考架构师
9***P3343 小时前
Rust在网络中的Rocket
开发语言·后端·rust
芯片智造3 小时前
光刻工艺工程师职场就业相关面试问题汇总
经验分享·面试·芯片·半导体
Wzx1980123 小时前
go聊天室
开发语言·后端·golang