github.com/go-eden/common@v0.1.15-0.20210617133546-059099253264/esync/sync_atomic_bool_test.go (about)

     1  package esync
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/stretchr/testify/assert"
     6  	"testing"
     7  )
     8  
     9  func TestAtomicBool(t *testing.T) {
    10  	var a AtomicBool
    11  
    12  	for i := 0; i < 100; i++ {
    13  		b := i%2 == 0
    14  		a.Set(b)
    15  		assert.True(t, a.Get() == b)
    16  		assert.True(t, a.Swap(true) == b && a.Get() == true)
    17  	}
    18  	multiRun(10, func() {
    19  		for i := 0; i < 1000000; i++ {
    20  			a.Set(true)
    21  			_ = a.Swap(false)
    22  			a.Get()
    23  		}
    24  	})
    25  	t.Log(a.String())
    26  }
    27  
    28  // BenchmarkAtomicBool_Set-12    	216363957	         5.621 ns/op
    29  func BenchmarkAtomicBool_Set(b *testing.B) {
    30  	var a AtomicBool
    31  	for i := 0; i < b.N; i++ {
    32  		a.Set(i&1 == 1)
    33  	}
    34  }
    35  
    36  // BenchmarkAtomicBool_Get-12    	1000000000	         0.2763 ns/op
    37  func BenchmarkAtomicBool_Get(b *testing.B) {
    38  	var a AtomicBool
    39  	for i := 0; i < b.N; i++ {
    40  		_ = a.Get()
    41  	}
    42  }
    43  
    44  // BenchmarkAtomicBool_Swap-12    	185458958	         6.179 ns/op
    45  func BenchmarkAtomicBool_Swap(b *testing.B) {
    46  	var a AtomicBool
    47  	for i := 0; i < b.N; i++ {
    48  		_ = a.Swap(i&1 == 1)
    49  	}
    50  }
    51  
    52  // ------------------------------------------------------------------------------
    53  func multiRun(concurrency int, f func()) {
    54  	signs := make(chan bool, concurrency)
    55  	for i := 0; i < concurrency; i++ {
    56  		go func() {
    57  			defer func() {
    58  				if e := recover(); e != nil {
    59  					fmt.Printf("RUN panic: %v", e)
    60  				}
    61  				signs <- true
    62  			}()
    63  			f()
    64  		}()
    65  	}
    66  	for i := 0; i < concurrency; i++ {
    67  		<-signs
    68  	}
    69  }