Reduce the maximum times of backoff in spin lock and update the tests

This commit is contained in:
Andy Pan 2021-11-27 20:21:45 +08:00
parent d3e3a334a3
commit 26d1224862
2 changed files with 4 additions and 24 deletions

View File

@ -12,7 +12,7 @@ import (
type spinLock uint32
const maxBackoff = 64
const maxBackoff = 16
func (sl *spinLock) Lock() {
backoff := 1

View File

@ -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()