github.com/liangmanlin/routine@v1.1.0/runtime_test.go (about)

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