-
Notifications
You must be signed in to change notification settings - Fork 9
/
goroutine_id.go
51 lines (40 loc) · 1.37 KB
/
goroutine_id.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Copyright ©2020 Dan Kortschak. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package goroutine provides a single function that will return the runtime's
// ID number for the calling goroutine.
//
// The implementation is derived from Laevus Dexter's comment in Gophers' Slack #darkarts,
// https://gophers.slack.com/archives/C1C1YSQBT/p1593885226448300 post which linked to
// this playground snippet https://play.golang.org/p/CSOp9wyzydP.
package ecs
import (
"reflect"
"unsafe"
)
// goroutineID returns the runtime ID of the calling goroutine.
func goroutineID() int64 {
return *(*int64)(add(getg(), goidoff))
}
func getg() unsafe.Pointer {
return *(*unsafe.Pointer)(add(getm(), curgoff))
}
//go:linkname add runtime.add
//go:nosplit
func add(p unsafe.Pointer, x uintptr) unsafe.Pointer
//go:linkname getm runtime.getm
func getm() unsafe.Pointer
var (
curgoff = offset("*runtime.m", "curg")
goidoff = offset("*runtime.g", "goid")
)
// offset returns the offset into typ for the given field.
func offset(typ, field string) uintptr {
rt := toType(typesByString(typ)[0])
f, _ := rt.Elem().FieldByName(field)
return f.Offset
}
//go:linkname typesByString reflect.typesByString
func typesByString(s string) []unsafe.Pointer
//go:linkname toType reflect.toType
func toType(t unsafe.Pointer) reflect.Type