1、修改锁范围
This commit is contained in:
parent
271b7daf65
commit
332aff0a41
19
spinlock.go
19
spinlock.go
@ -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
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user