github.com/lingyao2333/mo-zero@v1.4.1/core/syncx/spinlock.go (about) 1 package syncx 2 3 import ( 4 "runtime" 5 "sync/atomic" 6 ) 7 8 // A SpinLock is used as a lock a fast execution. 9 type SpinLock struct { 10 lock uint32 11 } 12 13 // Lock locks the SpinLock. 14 func (sl *SpinLock) Lock() { 15 for !sl.TryLock() { 16 runtime.Gosched() 17 } 18 } 19 20 // TryLock tries to lock the SpinLock. 21 func (sl *SpinLock) TryLock() bool { 22 return atomic.CompareAndSwapUint32(&sl.lock, 0, 1) 23 } 24 25 // Unlock unlocks the SpinLock. 26 func (sl *SpinLock) Unlock() { 27 atomic.StoreUint32(&sl.lock, 0) 28 }