1 Star 0 Fork 0

Stefan/go-zero

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
limit.go 1.08 KB
一键复制 编辑 原始数据 按行查看 历史
Stefan 提交于 2025-06-11 18:20 +08:00 . fix import package
package syncx
import (
"errors"
"gitee.com/emmm_admin/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
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/stefan886/go-zero.git
git@gitee.com:stefan886/go-zero.git
stefan886
go-zero
go-zero
45236c288c2b

搜索帮助