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

     1  package esync
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  	"testing"
     7  )
     8  
     9  func TestReMutex1(t *testing.T) {
    10  	var m ReMutex
    11  
    12  	m.Lock()
    13  	m.Lock()
    14  
    15  	m.Lock()
    16  	m.Unlock()
    17  	m.Lock()
    18  	m.Unlock()
    19  
    20  	m.Unlock()
    21  	m.Unlock()
    22  
    23  	for i := 0; i < 1000; i++ {
    24  		m.Lock()
    25  		m.Lock()
    26  		m.Unlock()
    27  		m.Unlock()
    28  	}
    29  }
    30  
    31  func TestReMutex2(t *testing.T) {
    32  	var m ReMutex
    33  
    34  	const num = 10
    35  	const max = 500
    36  
    37  	var doneCond = sync.NewCond(&m)
    38  	var conds [num]*sync.Cond
    39  	var counter int32
    40  
    41  	for i := 0; i < num; i++ {
    42  		conds[i] = sync.NewCond(&m)
    43  	}
    44  
    45  	for i := 0; i < num; i++ {
    46  		var group = int32(i)
    47  		go func() {
    48  			//gid := goid.Gid()
    49  			for atomic.LoadInt32(&counter) < max {
    50  				m.Lock()
    51  				if atomic.LoadInt32(&counter)%num == group {
    52  					//t.Log(gid, counter)
    53  					newCounter := atomic.AddInt32(&counter, 1)
    54  					conds[newCounter%num].Signal() // notify next goroutine
    55  				} else {
    56  					conds[group].Wait()
    57  				}
    58  				m.Unlock()
    59  			}
    60  			doneCond.Signal()
    61  		}()
    62  	}
    63  	m.Lock()
    64  	doneCond.Wait()
    65  	m.Unlock()
    66  }
    67  
    68  func TestReMutex3(t *testing.T) {
    69  
    70  }
    71  
    72  // BenchmarkRemutex-12    	39420012	        30.5 ns/op	       0 B/op	       0 allocs/op
    73  func BenchmarkRemutex(b *testing.B) {
    74  	var m ReMutex
    75  
    76  	b.ResetTimer()
    77  	b.ReportAllocs()
    78  
    79  	for i := 0; i < b.N; i++ {
    80  		m.Lock()
    81  		m.Lock()
    82  		m.Lock()
    83  		m.Unlock()
    84  		m.Lock()
    85  		m.Unlock()
    86  		m.Unlock()
    87  		m.Lock()
    88  		m.Unlock()
    89  		m.Unlock()
    90  	}
    91  }