go-zero/core/syncx/limit.go

49 lines
1.1 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import (
"errors"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/lang"
2020-07-26 17:09:05 +08:00
)
2020-10-10 11:53:49 +08:00
// 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")
2020-07-26 17:09:05 +08:00
2020-10-10 11:53:49 +08:00
// Limit controls the concurrent requests.
2020-07-26 17:09:05 +08:00
type Limit struct {
pool chan lang.PlaceholderType
}
2020-10-10 11:53:49 +08:00
// NewLimit creates a Limit that can borrow n elements from it concurrently.
2020-07-26 17:09:05 +08:00
func NewLimit(n int) Limit {
return Limit{
pool: make(chan lang.PlaceholderType, n),
}
}
2020-10-10 11:53:49 +08:00
// Borrow borrows an element from Limit in blocking mode.
2020-07-26 17:09:05 +08:00
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:
2020-10-10 11:53:49 +08:00
return ErrLimitReturn
2020-07-26 17:09:05 +08:00
}
}
2020-10-10 11:53:49 +08:00
// TryBorrow tries to borrow an element from Limit, in non-blocking mode.
// If success, true returned, false for otherwise.
2020-07-26 17:09:05 +08:00
func (l Limit) TryBorrow() bool {
select {
case l.pool <- lang.Placeholder:
return true
default:
return false
}
}