Compare commits

...

1 Commits
v1.0.0 ... main

Author SHA1 Message Date
332aff0a41 1、修改锁范围 2025-04-18 18:08:08 +08:00

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 {
case <-time.After(ttl):
return errors.New("lock timeout")
case <-ticker.C:
if err := s.tryLock(ttl); err == nil { if err := s.tryLock(ttl); err == nil {
return nil return nil
} }
} }
}
return nil
} }