-
Notifications
You must be signed in to change notification settings - Fork 1
/
goid_go_test.go
53 lines (49 loc) · 1.1 KB
/
goid_go_test.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
52
53
package unsafe_test
import (
"fmt"
"github.com/mzzsfy/go-util/unsafe"
"runtime"
"strings"
"sync"
"testing"
_ "unsafe"
)
func Test_GoID(t *testing.T) {
var wg sync.WaitGroup
for i := 0; i < 5000; i++ {
wg.Add(1)
go func() {
testGoID(t)
wg.Done()
}()
}
wg.Wait()
}
func testGoID(t *testing.T) {
id := unsafe.GoID()
lines := strings.Split(stackTrace(), "\n")
for i, line := range lines {
if !strings.HasPrefix(line, fmt.Sprintf("goroutine %d ", id)) {
continue
}
if i+1 == len(lines) {
break
}
if !strings.Contains(lines[i+1], ".stackTrace") {
t.Errorf("there are goroutine id %d but it is not me: %s", id, lines[i+1])
}
return
}
t.Errorf("there are no goroutine %d", id)
}
func stackTrace() string {
var n int
for n = 4096; n < 16777216; n *= 2 {
buf := make([]byte, n)
ret := runtime.Stack(buf, false)
if ret != n {
return string(buf[:ret])
}
}
panic(n)
}