spinlock.go 326 B

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