forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeoutlimit.go
57 lines (47 loc) · 974 Bytes
/
timeoutlimit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package syncx
import (
"errors"
"time"
)
// ErrTimeout is an error that indicates the borrow timeout.
var ErrTimeout = errors.New("borrow timeout")
// A TimeoutLimit is used to borrow with timeouts.
type TimeoutLimit struct {
limit Limit
cond *Cond
}
// NewTimeoutLimit returns a TimeoutLimit.
func NewTimeoutLimit(n int) TimeoutLimit {
return TimeoutLimit{
limit: NewLimit(n),
cond: NewCond(),
}
}
// Borrow borrows with given timeout.
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.
func (l TimeoutLimit) Return() error {
if err := l.limit.Return(); err != nil {
return err
}
l.cond.Signal()
return nil
}
// TryBorrow tries a borrow.
func (l TimeoutLimit) TryBorrow() bool {
return l.limit.TryBorrow()
}