Documentation
¶
Overview ¶
Package semaphore 提供加权信号量原语:限制对共享资源的最大并发占用量。
与 channel-based 等权信号量不同,本包支持**加权获取**:每次 Acquire 可指定 cost, 适用于"重操作占 5 槽、轻操作占 1 槽"的场景。等权场景(bulkhead/舱壁隔离) 是 cost=1 的特殊情况,直接用 Do(ctx, fn) 即可。
与 ratelimit(限速率/每秒多少) 互补: semaphore 限的是**同时占用**的容量。 与 circuitbreaker(按错误率熔断) 互补: semaphore 在错误率未达阈值时就能限并发。
纯标准库、并发安全。
Index ¶
- Variables
- type Option
- type Semaphore
- func (s *Semaphore) Acquire(ctx context.Context, cost int64) error
- func (s *Semaphore) Available() int64
- func (s *Semaphore) Capacity() int64
- func (s *Semaphore) Do(ctx context.Context, fn func() error) error
- func (s *Semaphore) DoWithCost(ctx context.Context, cost int64, fn func() error) error
- func (s *Semaphore) InFlight() int64
- func (s *Semaphore) Release(cost int64)
- func (s *Semaphore) TryAcquire(cost int64) bool
Constants ¶
This section is empty.
Variables ¶
View Source
var ErrFull = errors.New("semaphore: full")
ErrFull 表示信号量已满,请求被拒绝。
Functions ¶
This section is empty.
Types ¶
type Semaphore ¶
type Semaphore struct {
// contains filtered or unexported fields
}
Semaphore 加权信号量。并发安全。
func (*Semaphore) Acquire ¶
Acquire 获取 cost 个单位的容量。阻塞直到可用、超时或 context 取消。 cost 必须 > 0 且 <= capacity,否则 panic。
func (*Semaphore) DoWithCost ¶
DoWithCost 加权便捷方法:获取 cost 个单位 → 执行 fn → 自动释放。
func (*Semaphore) TryAcquire ¶
TryAcquire 非阻塞尝试获取。成功返回 true。
Click to show internal directories.
Click to hide internal directories.