From 26d1224862d03d7fae7d63a3b242132343675dfd Mon Sep 17 00:00:00 2001 From: Andy Pan Date: Sat, 27 Nov 2021 20:21:45 +0800 Subject: [PATCH] Reduce the maximum times of backoff in spin lock and update the tests --- internal/spinlock.go | 2 +- internal/spinlock_test.go | 26 +++----------------------- 2 files changed, 4 insertions(+), 24 deletions(-) diff --git a/internal/spinlock.go b/internal/spinlock.go index 5e8572c..6261f74 100644 --- a/internal/spinlock.go +++ b/internal/spinlock.go @@ -12,7 +12,7 @@ import ( type spinLock uint32 -const maxBackoff = 64 +const maxBackoff = 16 func (sl *spinLock) Lock() { backoff := 1 diff --git a/internal/spinlock_test.go b/internal/spinlock_test.go index 27d57ab..cabf5e7 100644 --- a/internal/spinlock_test.go +++ b/internal/spinlock_test.go @@ -34,30 +34,10 @@ func (sl *originSpinLock) Unlock() { atomic.StoreUint32((*uint32)(sl), 0) } -func GetOriginSpinLock() sync.Locker { +func NewOriginSpinLock() sync.Locker { return new(originSpinLock) } -type backOffSpinLock uint32 - -func (sl *backOffSpinLock) Lock() { - wait := 1 - for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) { - for i := 0; i < wait; i++ { - runtime.Gosched() - } - wait <<= 1 - } -} - -func (sl *backOffSpinLock) Unlock() { - atomic.StoreUint32((*uint32)(sl), 0) -} - -func GetBackOffSpinLock() sync.Locker { - return new(backOffSpinLock) -} - func BenchmarkMutex(b *testing.B) { m := sync.Mutex{} b.RunParallel(func(pb *testing.PB) { @@ -70,7 +50,7 @@ func BenchmarkMutex(b *testing.B) { } func BenchmarkSpinLock(b *testing.B) { - spin := GetOriginSpinLock() + spin := NewOriginSpinLock() b.RunParallel(func(pb *testing.PB) { for pb.Next() { spin.Lock() @@ -81,7 +61,7 @@ func BenchmarkSpinLock(b *testing.B) { } func BenchmarkBackOffSpinLock(b *testing.B) { - spin := GetBackOffSpinLock() + spin := NewSpinLock() b.RunParallel(func(pb *testing.PB) { for pb.Next() { spin.Lock()