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/limit.go

49 lines
1.1 KiB
Go

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