SpinLock.go 334 B

123456789101112131415161718192021222324
  1. package base
  2. import (
  3. "runtime"
  4. "sync"
  5. "sync/atomic"
  6. )
  7. type spinLock uint32
  8. func (sl *spinLock) Lock() {
  9. for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
  10. runtime.Gosched()
  11. }
  12. }
  13. func (sl *spinLock) Unlock() {
  14. atomic.StoreUint32((*uint32)(sl), 0)
  15. }
  16. func NewSpinLock() sync.Locker {
  17. var lock spinLock
  18. return &lock
  19. }