-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
limit.go
48 lines (40 loc) · 1.08 KB
/
limit.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
package syncx
import (
"errors"
"github.com/tal-tech/go-zero/core/lang"
)
// ErrLimitReturn indicates that the more than borrowed elements were returned.
var ErrLimitReturn = errors.New("discarding limited token, resource pool is full, someone returned multiple times")
// Limit controls the concurrent requests.
type Limit struct {
pool chan lang.PlaceholderType
}
// NewLimit creates a Limit that can borrow n elements from it concurrently.
func NewLimit(n int) Limit {
return Limit{
pool: make(chan lang.PlaceholderType, n),
}
}
// Borrow borrows an element from Limit in blocking mode.
func (l Limit) Borrow() {
l.pool <- lang.Placeholder
}
// Return returns the borrowed resource, returns error only if returned more than borrowed.
func (l Limit) Return() error {
select {
case <-l.pool:
return nil
default:
return ErrLimitReturn
}
}
// TryBorrow tries to borrow an element from Limit, in non-blocking mode.
// If success, true returned, false for otherwise.
func (l Limit) TryBorrow() bool {
select {
case l.pool <- lang.Placeholder:
return true
default:
return false
}
}