首先看一下指数退避算法的维基百科解释
看不了的直接看图片吧
在go 协成池框架中有一把巧妙的锁:spinLock
import (
"runtime"
"sync"
"sync/atomic"
)
type spinLock uint32
const maxBackoff = 64
func (sl *spinLock) Lock() {
backoff := 1
// 巧妙之处
for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
// Leverage the exponential backoff algorithm 利用指数退避算法
for i := 0; i < backoff; i++ {
runtime.Gosched()
}
if backoff < maxBackoff {
backoff <<= 1
}
}
}
func (sl *spinLock) Unlock() {
atomic.StoreUint32((*uint32)(sl), 0)
}
// NewSpinLock instantiates a spin-lock.
func NewSpinLock() sync.Locker {
return new(spinLock)
}