github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/runtimer/goroutine_test.go (about)

     1  package runtimer
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  import (
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  func TestGoSafe(t *testing.T) {
    15  	times := int32(1)
    16  
    17  	var wg sync.WaitGroup
    18  	GoSafely(&wg,
    19  		false,
    20  		func() {
    21  			panic("hello")
    22  		},
    23  		func(r interface{}) {
    24  			atomic.AddInt32(&times, 1)
    25  		}, nil,
    26  	)
    27  
    28  	wg.Wait()
    29  	assert.True(t, atomic.LoadInt32(&times) == 2)
    30  
    31  	GoSafely(nil,
    32  		false,
    33  		func() {
    34  			panic("hello")
    35  		},
    36  		func(r interface{}) {
    37  			atomic.AddInt32(&times, 1)
    38  		}, nil,
    39  	)
    40  	time.Sleep(1e9)
    41  	assert.True(t, atomic.LoadInt32(&times) == 3)
    42  }
    43  
    44  func TestGoUnterminated(t *testing.T) {
    45  	times := uint64(1)
    46  	var wg sync.WaitGroup
    47  	GoUnterminated(
    48  		func() {
    49  			if atomic.AddUint64(&times, 1) == 2 {
    50  				panic("hello")
    51  			}
    52  		},
    53  		&wg,
    54  		false,
    55  		1e8, nil,
    56  	)
    57  	wg.Wait()
    58  	assert.True(t, atomic.LoadUint64(&times) == 3)
    59  
    60  	GoUnterminated(func() {
    61  		atomic.AddUint64(&times, 1)
    62  	},
    63  		nil,
    64  		false,
    65  		1e8, nil,
    66  	)
    67  	time.Sleep(1e9)
    68  	assert.True(t, atomic.LoadUint64(&times) == 4)
    69  }