You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/syncx/timeoutlimit.go

58 lines
974 B
Go

4 years ago
package syncx
import (
"errors"
"time"
)
// ErrTimeout is an error that indicates the borrow timeout.
4 years ago
var ErrTimeout = errors.New("borrow timeout")
// A TimeoutLimit is used to borrow with timeouts.
4 years ago
type TimeoutLimit struct {
limit Limit
cond *Cond
}
// NewTimeoutLimit returns a TimeoutLimit.
4 years ago
func NewTimeoutLimit(n int) TimeoutLimit {
return TimeoutLimit{
limit: NewLimit(n),
cond: NewCond(),
}
}
// Borrow borrows with given timeout.
4 years ago
func (l TimeoutLimit) Borrow(timeout time.Duration) error {
if l.TryBorrow() {
return nil
}
var ok bool
for {
timeout, ok = l.cond.WaitWithTimeout(timeout)
if ok && l.TryBorrow() {
return nil
}
if timeout <= 0 {
return ErrTimeout
}
}
}
// Return returns a borrow.
4 years ago
func (l TimeoutLimit) Return() error {
if err := l.limit.Return(); err != nil {
return err
}
l.cond.Signal()
return nil
}
// TryBorrow tries a borrow.
4 years ago
func (l TimeoutLimit) TryBorrow() bool {
return l.limit.TryBorrow()
}