github.com/timandy/routine@v1.1.4/runtime_test.go (about) 1 package routine 2 3 import ( 4 "fmt" 5 "os" 6 "reflect" 7 "runtime" 8 "sync" 9 "sync/atomic" 10 "testing" 11 "unsafe" 12 13 "github.com/stretchr/testify/assert" 14 ) 15 16 //go:linkname packEface github.com/timandy/routine/g.packEface 17 func packEface(typ reflect.Type, p unsafe.Pointer) (i any) 18 19 func TestGetgp(t *testing.T) { 20 gp0 := getgp() 21 runtime.GC() 22 assert.NotNil(t, gp0) 23 // 24 runTest(t, func() { 25 gp := getgp() 26 runtime.GC() 27 assert.NotNil(t, gp) 28 assert.NotEqual(t, gp0, gp) 29 }) 30 } 31 32 func TestGetgt(t *testing.T) { 33 fmt.Println("*** GOOS:", runtime.GOOS, "***") 34 fmt.Println("*** GOARCH:", runtime.GOARCH, "***") 35 if GOARM := os.Getenv("GOARM"); len(GOARM) > 0 { 36 fmt.Println("*** GOARM:", GOARM, "***") 37 } 38 if GOMIPS := os.Getenv("GOMIPS"); len(GOMIPS) > 0 { 39 fmt.Println("*** GOMIPS:", GOMIPS, "***") 40 } 41 // 42 gt := getgt() 43 runtime.GC() 44 assert.Equal(t, "g", gt.Name()) 45 // 46 numField := gt.NumField() 47 // 48 fmt.Println("#numField:", numField) 49 fmt.Println("#offsetGoid:", offsetGoid) 50 fmt.Println("#offsetPaniconfault:", offsetPaniconfault) 51 fmt.Println("#offsetGopc:", offsetGopc) 52 fmt.Println("#offsetLabels:", offsetLabels) 53 // 54 assert.Greater(t, numField, 20) 55 assert.Greater(t, int(offsetGoid), 0) 56 assert.Greater(t, int(offsetPaniconfault), 0) 57 assert.Greater(t, int(offsetGopc), 0) 58 assert.Greater(t, int(offsetLabels), 0) 59 // 60 runTest(t, func() { 61 tt := getgt() 62 runtime.GC() 63 assert.Equal(t, numField, tt.NumField()) 64 assert.Equal(t, offsetGoid, offset(tt, "goid")) 65 assert.Equal(t, offsetPaniconfault, offset(tt, "paniconfault")) 66 assert.Equal(t, offsetGopc, offset(tt, "gopc")) 67 assert.Equal(t, offsetLabels, offset(tt, "labels")) 68 }) 69 } 70 71 func TestGetg(t *testing.T) { 72 runTest(t, func() { 73 g0 := packEface(getgt(), getgp()) 74 runtime.GC() 75 stackguard0 := reflect.ValueOf(g0).FieldByName("stackguard0") 76 assert.Greater(t, stackguard0.Uint(), uint64(0)) 77 }) 78 } 79 80 func runTest(t *testing.T, fun func()) { 81 var count int32 82 wg := &sync.WaitGroup{} 83 wg.Add(10) 84 for i := 0; i < 10; i++ { 85 go func() { 86 for j := 0; j < 10; j++ { 87 fun() 88 } 89 atomic.AddInt32(&count, 1) 90 wg.Done() 91 }() 92 } 93 wg.Wait() 94 assert.Equal(t, 10, int(count)) 95 }