github.com/GoWebProd/gip@v0.0.0-20230623090727-b60d41d5d320/spinlock/spinlock_test.go (about) 1 package spinlock 2 3 import ( 4 "sync" 5 "testing" 6 ) 7 8 func testLock(b *testing.B, threads int, l sync.Locker) { 9 var wg sync.WaitGroup 10 wg.Add(threads) 11 12 var count1 int 13 var count2 int 14 15 for i := 0; i < threads; i++ { 16 go func() { 17 for i := 0; i < b.N; i++ { 18 l.Lock() 19 count1++ 20 count2 += 2 21 l.Unlock() 22 } 23 wg.Done() 24 }() 25 } 26 27 wg.Wait() 28 29 if count1 != threads*b.N { 30 b.Fatal("mismatch") 31 } 32 if count2 != threads*b.N*2 { 33 b.Fatal("mismatch") 34 } 35 } 36 37 func BenchmarkSpinlock_1(b *testing.B) { 38 testLock(b, 1, &Locker{}) 39 } 40 41 func BenchmarkSpinlock_6(b *testing.B) { 42 testLock(b, 6, &Locker{}) 43 } 44 45 func BenchmarkSpinlock_12(b *testing.B) { 46 testLock(b, 12, &Locker{}) 47 } 48 49 func BenchmarkMutex_1(b *testing.B) { 50 testLock(b, 1, &sync.Mutex{}) 51 } 52 53 func BenchmarkMutex_6(b *testing.B) { 54 testLock(b, 6, &sync.Mutex{}) 55 } 56 57 func BenchmarkMutex_12(b *testing.B) { 58 testLock(b, 12, &sync.Mutex{}) 59 }