Compare commits
1 Commits
Author | SHA1 | Date | |
---|---|---|---|
332aff0a41 |
15
spinlock.go
15
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 {
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user