github.com/liangmanlin/routine@v1.1.0/routine_test.go (about) 1 package routine 2 3 import ( 4 "bytes" 5 "context" 6 "github.com/stretchr/testify/assert" 7 "runtime/pprof" 8 "sync" 9 "testing" 10 "time" 11 "unsafe" 12 ) 13 14 func TestCurrentThread(t *testing.T) { 15 assert.NotNil(t, currentThread(true)) 16 assert.Same(t, currentThread(true), currentThread(true)) 17 } 18 19 func TestPProf(t *testing.T) { 20 const concurrency = 10 21 const loopTimes = 10 22 val := 1 23 Set(unsafe.Pointer(&val)) 24 wg := &sync.WaitGroup{} 25 wg.Add(concurrency) 26 for i := 0; i < concurrency; i++ { 27 tmp := i 28 go func() { 29 for j := 0; j < loopTimes; j++ { 30 time.Sleep(100 * time.Millisecond) 31 Set(unsafe.Pointer(&tmp)) 32 assert.Equal(t, tmp, *Get[int]()) 33 pprof.Do(context.Background(), pprof.Labels("key", "value"), func(ctx context.Context) { 34 assert.Nil(t, currentThread(false)) 35 assert.Nil(t, Get[int]()) 36 Set(unsafe.Pointer(&tmp)) 37 // 38 label, find := pprof.Label(ctx, "key") 39 assert.True(t, find) 40 assert.Equal(t, "value", label) 41 // 42 assert.Equal(t, tmp, *Get[int]()) 43 // 44 label2, find2 := pprof.Label(ctx, "key") 45 assert.True(t, find2) 46 assert.Equal(t, "value", label2) 47 }) 48 assert.Nil(t, Get[int]()) 49 } 50 wg.Done() 51 }() 52 } 53 assert.Nil(t, pprof.StartCPUProfile(&bytes.Buffer{})) 54 wg.Wait() 55 pprof.StopCPUProfile() 56 assert.Equal(t, val, *Get[int]()) 57 } 58 59 func BenchmarkGet(b *testing.B) { 60 val := []int{1, 23, 4, 1, 4, 4, 5} 61 Set(unsafe.Pointer(&val)) 62 b.ResetTimer() 63 for i := 0; i < b.N; i++ { 64 _ = Get[[]int]() 65 } 66 }