You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/syncx/spinlock.go

29 lines
475 B
Go

4 years ago
package syncx
import (
"runtime"
"sync/atomic"
)
// A SpinLock is used as a lock a fast execution.
4 years ago
type SpinLock struct {
lock uint32
}
// Lock locks the SpinLock.
4 years ago
func (sl *SpinLock) Lock() {
for !sl.TryLock() {
runtime.Gosched()
}
}
// TryLock tries to lock the SpinLock.
4 years ago
func (sl *SpinLock) TryLock() bool {
return atomic.CompareAndSwapUint32(&sl.lock, 0, 1)
}
// Unlock unlocks the SpinLock.
4 years ago
func (sl *SpinLock) Unlock() {
atomic.StoreUint32(&sl.lock, 0)
}