gitee.com/quant1x/gox@v1.21.2/gls/goid_test.go (about) 1 package gls 2 3 import ( 4 "fmt" 5 "runtime" 6 "strings" 7 "sync" 8 "testing" 9 _ "unsafe" 10 ) 11 12 func TestGoID(t *testing.T) { 13 var wg sync.WaitGroup 14 for i := 0; i < 5; i++ { 15 wg.Add(1) 16 go func() { 17 testGoID(t) 18 wg.Done() 19 }() 20 } 21 wg.Wait() 22 } 23 24 func testGoID(t *testing.T) { 25 id := GoID() 26 lines := strings.Split(stackTrace(), "\n") 27 for i, line := range lines { 28 if !strings.HasPrefix(line, fmt.Sprintf("goroutine %d ", id)) { 29 continue 30 } 31 if i+1 == len(lines) { 32 break 33 } 34 if !strings.Contains(lines[i+1], ".stackTrace") { 35 t.Errorf("there are goroutine id %d but it is not me: %s", id, lines[i+1]) 36 } 37 return 38 } 39 t.Errorf("there are no goroutine %d", id) 40 } 41 42 func stackTrace() string { 43 var n int 44 for n = 4096; n < 16777216; n *= 2 { 45 buf := make([]byte, n) 46 ret := runtime.Stack(buf, true) 47 if ret != n { 48 return string(buf[:ret]) 49 } 50 } 51 panic(n) 52 } 53 54 func TestGoID1(t *testing.T) { 55 gid := GoID() 56 fmt.Println(gid) 57 }