spinlock.go 475 B

12345678910111213141516171819202122232425262728
  1. package syncx
  2. import (
  3. "runtime"
  4. "sync/atomic"
  5. )
  6. // A SpinLock is used as a lock a fast execution.
  7. type SpinLock struct {
  8. lock uint32
  9. }
  10. // Lock locks the SpinLock.
  11. func (sl *SpinLock) Lock() {
  12. for !sl.TryLock() {
  13. runtime.Gosched()
  14. }
  15. }
  16. // TryLock tries to lock the SpinLock.
  17. func (sl *SpinLock) TryLock() bool {
  18. return atomic.CompareAndSwapUint32(&sl.lock, 0, 1)
  19. }
  20. // Unlock unlocks the SpinLock.
  21. func (sl *SpinLock) Unlock() {
  22. atomic.StoreUint32(&sl.lock, 0)
  23. }