github.com/dubbogo/gost@v1.14.0/runtime/goroutine_test.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package gxruntime
    19  
    20  import (
    21  	"sync"
    22  	"sync/atomic"
    23  	"testing"
    24  	"time"
    25  )
    26  
    27  import (
    28  	"github.com/stretchr/testify/assert"
    29  )
    30  
    31  func TestGoSafe(t *testing.T) {
    32  	times := int32(1)
    33  
    34  	var wg sync.WaitGroup
    35  	GoSafely(&wg,
    36  		false,
    37  		func() {
    38  			panic("hello")
    39  		},
    40  		func(r interface{}) {
    41  			atomic.AddInt32(&times, 1)
    42  		},
    43  	)
    44  
    45  	wg.Wait()
    46  	assert.True(t, atomic.LoadInt32(&times) == 2)
    47  
    48  	GoSafely(nil,
    49  		false,
    50  		func() {
    51  			panic("hello")
    52  		},
    53  		func(r interface{}) {
    54  			atomic.AddInt32(&times, 1)
    55  		},
    56  	)
    57  	time.Sleep(1e9)
    58  	assert.True(t, atomic.LoadInt32(&times) == 3)
    59  }
    60  
    61  func TestGoUnterminated(t *testing.T) {
    62  	times := uint64(1)
    63  	var wg sync.WaitGroup
    64  	GoUnterminated(
    65  		func() {
    66  			if atomic.AddUint64(&times, 1) == 2 {
    67  				panic("hello")
    68  			}
    69  		},
    70  		&wg,
    71  		false,
    72  		1e8,
    73  	)
    74  	wg.Wait()
    75  	assert.True(t, atomic.LoadUint64(&times) == 3)
    76  
    77  	GoUnterminated(func() {
    78  		atomic.AddUint64(&times, 1)
    79  	},
    80  		nil,
    81  		false,
    82  		1e8,
    83  	)
    84  	time.Sleep(1e9)
    85  	assert.True(t, atomic.LoadUint64(&times) == 4)
    86  }