Skip to content

Commit

Permalink
Reduce the maximum times of backoff in spin lock and update the tests
Browse files Browse the repository at this point in the history
  • Loading branch information
panjf2000 committed Nov 27, 2021
1 parent d3e3a33 commit 26d1224
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 24 deletions.
2 changes: 1 addition & 1 deletion internal/spinlock.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (

type spinLock uint32

const maxBackoff = 64
const maxBackoff = 16

func (sl *spinLock) Lock() {
backoff := 1
Expand Down
26 changes: 3 additions & 23 deletions internal/spinlock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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()
Expand All @@ -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()
Expand Down

0 comments on commit 26d1224

Please sign in to comment.