github.com/songzhibin97/gkit@v1.2.13/sys/mutex/mutex_test.go (about)

     1  package mutex
     2  
     3  import (
     4  	"runtime"
     5  	"sync"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/songzhibin97/gkit/internal/clock"
    10  )
    11  
    12  func Test_Mutex_TryLock(t *testing.T) {
    13  	var m Mutex
    14  	m.Lock()
    15  	clock.Sleep(time.Second)
    16  	if m.TryLock() {
    17  		t.Error("TryLock get lock error")
    18  	}
    19  	m.Unlock()
    20  	if !m.TryLock() {
    21  		t.Error("TryLock get lock error")
    22  	}
    23  	m.Unlock()
    24  }
    25  
    26  func utTriableMutexConcurrent(t *testing.T) {
    27  	m := &Mutex{}
    28  	cnt := int32(0)
    29  	wg := &sync.WaitGroup{}
    30  	wg.Add(1000)
    31  	for i := 0; i < 1000; i++ {
    32  		go func(tm *Mutex, wgi *sync.WaitGroup, cntPtr *int32, t *testing.T) {
    33  			for {
    34  				if tm.TryLock() {
    35  					*cntPtr = *cntPtr + 1
    36  					tm.Unlock()
    37  					wgi.Done()
    38  					break
    39  				} else {
    40  					runtime.Gosched()
    41  				}
    42  			}
    43  		}(m, wg, &cnt, t)
    44  	}
    45  	wg.Wait()
    46  	// fmt.Println("count=", cnt)
    47  	if cnt != 1000 {
    48  		t.Error("count error concurrency")
    49  	}
    50  }
    51  
    52  func Test_Mutex_TryLock_Concurrent(t *testing.T) {
    53  	utTriableMutexConcurrent(t)
    54  }
    55  
    56  func Benchmark_Mutex_TryLock(b *testing.B) {
    57  	for n := 0; n < b.N; n++ {
    58  		utTriableMutexConcurrent(nil)
    59  	}
    60  }