1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 00:22:41 +08:00
Files
go-mixed/locker/spin_locker.go
2022-06-07 10:57:42 +08:00

27 lines
414 B
Go

package locker
import (
"runtime"
"sync/atomic"
)
type spinLock uint32
func NewSpinLocker() *spinLock {
return new(spinLock)
}
func (sl *spinLock) TryLock() bool {
return atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1)
}
func (sl *spinLock) Lock() {
for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
runtime.Gosched()
}
}
func (sl *spinLock) Unlock() {
atomic.StoreUint32((*uint32)(sl), 0)
}