go-zero/core/syncx/timeoutlimit.go

58 lines
974 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import (
"errors"
"time"
)
2021-02-28 16:16:22 +08:00
// ErrTimeout is an error that indicates the borrow timeout.
2020-07-26 17:09:05 +08:00
var ErrTimeout = errors.New("borrow timeout")
2021-02-28 16:16:22 +08:00
// A TimeoutLimit is used to borrow with timeouts.
2020-07-26 17:09:05 +08:00
type TimeoutLimit struct {
limit Limit
cond *Cond
}
2021-02-28 16:16:22 +08:00
// NewTimeoutLimit returns a TimeoutLimit.
2020-07-26 17:09:05 +08:00
func NewTimeoutLimit(n int) TimeoutLimit {
return TimeoutLimit{
limit: NewLimit(n),
cond: NewCond(),
}
}
2021-02-28 16:16:22 +08:00
// Borrow borrows with given timeout.
2020-07-26 17:09:05 +08:00
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
}
}
}
2021-02-28 16:16:22 +08:00
// Return returns a borrow.
2020-07-26 17:09:05 +08:00
func (l TimeoutLimit) Return() error {
if err := l.limit.Return(); err != nil {
return err
}
l.cond.Signal()
return nil
}
2021-02-28 16:16:22 +08:00
// TryBorrow tries a borrow.
2020-07-26 17:09:05 +08:00
func (l TimeoutLimit) TryBorrow() bool {
return l.limit.TryBorrow()
}