From 2728dcafeb5abae32e0c34293170a65e69b75e1f Mon Sep 17 00:00:00 2001 From: charlie <3140647@qq.com> Date: Thu, 2 Jun 2022 15:39:51 +0800 Subject: [PATCH] spin locker --- locker/spin_locker.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 locker/spin_locker.go diff --git a/locker/spin_locker.go b/locker/spin_locker.go new file mode 100644 index 0000000..8db0e44 --- /dev/null +++ b/locker/spin_locker.go @@ -0,0 +1,22 @@ +package locker + +import ( + "runtime" + "sync/atomic" +) + +type spinLock uint32 + +func NewSpinLocker() *spinLock { + return new(spinLock) +} + +func (sl *spinLock) Lock() { + for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) { + runtime.Gosched() + } +} + +func (sl *spinLock) Unlock() { + atomic.StoreUint32((*uint32)(sl), 0) +}