github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zsync/mutex_test.go (about)

     1  package zsync
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/sohaha/zlsgo"
     7  )
     8  
     9  func TestRBMutex(t *testing.T) {
    10  	tt := zlsgo.NewTest(t)
    11  
    12  	var (
    13  		wg    WaitGroup
    14  		total = 100
    15  		maps  = make(map[int]int)
    16  		mu    = NewRBMutex()
    17  	)
    18  
    19  	for i := 0; i < total; i++ {
    20  		maps[i] = i
    21  	}
    22  
    23  	for i := 0; i < total; i++ {
    24  		ii := i
    25  		wg.Go(func() {
    26  			mu.Lock()
    27  			maps[ii*2] = ii * 2
    28  			mu.Unlock()
    29  		})
    30  
    31  		wg.Go(func() {
    32  			t := mu.RLock()
    33  			tt.Equal(ii, maps[ii])
    34  			mu.RUnlock(t)
    35  		})
    36  	}
    37  
    38  	wg.Wait()
    39  }