用golang实现一个自旋锁

In software engineering, a spinlock is a lock which causes a thread trying to acquire it to simply wait in a loop (“spin”) while repeatedly checking if the lock is available(摘自wikipedia)。

利用cpu提供的原子原语来实现。

直接上码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type spinLock uint32
func (sl *spinLock) () {
for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
runtime.Gosched()
}
}
func (sl *spinLock) Unlock() {
atomic.StoreUint32((*uint32)(sl), 0)
}
func NewSpinLock() sync.Locker {
var lock spinLock
return &lock
}