1、修改锁范围

This commit is contained in:
redhat 2025-04-18 18:08:08 +08:00
parent 271b7daf65
commit 332aff0a41

View File

@ -20,9 +20,6 @@ func NewSpin() *Spin {
} }
func (s *Spin) tryLock(ttl time.Duration) error { func (s *Spin) tryLock(ttl time.Duration) error {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now() now := time.Now()
if !s.locked || now.After(s.expire) { if !s.locked || now.After(s.expire) {
s.locked = true s.locked = true
@ -54,6 +51,9 @@ func (s *Spin) Unlock() error {
} }
func (s *Spin) Lock(ttl time.Duration) error { func (s *Spin) Lock(ttl time.Duration) error {
s.mu.Lock()
defer s.mu.Unlock()
err := s.tryLock(ttl) err := s.tryLock(ttl)
if err == nil { if err == nil {
@ -67,14 +67,11 @@ func (s *Spin) Lock(ttl time.Duration) error {
ticker := time.NewTicker(20 * time.Millisecond) ticker := time.NewTicker(20 * time.Millisecond)
defer ticker.Stop() defer ticker.Stop()
for { for range ticker.C {
select { if err := s.tryLock(ttl); err == nil {
case <-time.After(ttl): return nil
return errors.New("lock timeout")
case <-ticker.C:
if err := s.tryLock(ttl); err == nil {
return nil
}
} }
} }
return nil
} }