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 {
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
}