go-zero/core/syncx/spinlock.go

29 lines
475 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import (
"runtime"
"sync/atomic"
)
2021-02-28 16:16:22 +08:00
// A SpinLock is used as a lock a fast execution.
2020-07-26 17:09:05 +08:00
type SpinLock struct {
lock uint32
}
2021-02-28 16:16:22 +08:00
// Lock locks the SpinLock.
2020-07-26 17:09:05 +08:00
func (sl *SpinLock) Lock() {
for !sl.TryLock() {
runtime.Gosched()
}
}
2021-02-28 16:16:22 +08:00
// TryLock tries to lock the SpinLock.
2020-07-26 17:09:05 +08:00
func (sl *SpinLock) TryLock() bool {
return atomic.CompareAndSwapUint32(&sl.lock, 0, 1)
}
2021-02-28 16:16:22 +08:00
// Unlock unlocks the SpinLock.
2020-07-26 17:09:05 +08:00
func (sl *SpinLock) Unlock() {
atomic.StoreUint32(&sl.lock, 0)
}