From 332aff0a410f0eb6c538e9e7b15286ffeb132e0c Mon Sep 17 00:00:00 2001 From: redhat <2292650292@qq.com> Date: Fri, 18 Apr 2025 18:08:08 +0800 Subject: [PATCH] =?UTF-8?q?1=E3=80=81=E4=BF=AE=E6=94=B9=E9=94=81=E8=8C=83?= =?UTF-8?q?=E5=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spinlock.go | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/spinlock.go b/spinlock.go index 84faea4..843b4fd 100644 --- a/spinlock.go +++ b/spinlock.go @@ -20,9 +20,6 @@ func NewSpin() *Spin { } func (s *Spin) tryLock(ttl time.Duration) error { - s.mu.Lock() - defer s.mu.Unlock() - now := time.Now() if !s.locked || now.After(s.expire) { s.locked = true @@ -54,6 +51,9 @@ func (s *Spin) Unlock() error { } func (s *Spin) Lock(ttl time.Duration) error { + s.mu.Lock() + defer s.mu.Unlock() + err := s.tryLock(ttl) if err == nil { @@ -67,14 +67,11 @@ func (s *Spin) Lock(ttl time.Duration) error { ticker := time.NewTicker(20 * time.Millisecond) defer ticker.Stop() - for { - select { - case <-time.After(ttl): - return errors.New("lock timeout") - case <-ticker.C: - if err := s.tryLock(ttl); err == nil { - return nil - } + for range ticker.C { + if err := s.tryLock(ttl); err == nil { + return nil } } + + return nil }