semaphore

package
v0.8.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 16, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package semaphore 提供加权信号量原语:限制对共享资源的最大并发占用量。

与 channel-based 等权信号量不同,本包支持**加权获取**:每次 Acquire 可指定 cost, 适用于"重操作占 5 槽、轻操作占 1 槽"的场景。等权场景(bulkhead/舱壁隔离) 是 cost=1 的特殊情况,直接用 Do(ctx, fn) 即可。

与 ratelimit(限速率/每秒多少) 互补: semaphore 限的是**同时占用**的容量。 与 circuitbreaker(按错误率熔断) 互补: semaphore 在错误率未达阈值时就能限并发。

纯标准库、并发安全。

Index

Constants

This section is empty.

Variables

View Source
var ErrFull = errors.New("semaphore: full")

ErrFull 表示信号量已满,请求被拒绝。

Functions

This section is empty.

Types

type Option

type Option func(*config)

Option 配置 Semaphore。

func WithCapacity

func WithCapacity(n int64) Option

WithCapacity 设置总容量(默认 10)。

func WithMaxWait

func WithMaxWait(d time.Duration) Option

WithMaxWait 设置等待获取的最大时间(默认 0,即满则立即拒绝)。

func WithOnReject

func WithOnReject(fn func()) Option

WithOnReject 注册被拒绝时的回调(用于计数/告警)。

type Semaphore

type Semaphore struct {
	// contains filtered or unexported fields
}

Semaphore 加权信号量。并发安全。

func New

func New(opts ...Option) *Semaphore

New 创建信号量。

func (*Semaphore) Acquire

func (s *Semaphore) Acquire(ctx context.Context, cost int64) error

Acquire 获取 cost 个单位的容量。阻塞直到可用、超时或 context 取消。 cost 必须 > 0 且 <= capacity,否则 panic。

func (*Semaphore) Available

func (s *Semaphore) Available() int64

Available 返回当前可用容量。

func (*Semaphore) Capacity

func (s *Semaphore) Capacity() int64

Capacity 返回总容量。

func (*Semaphore) Do

func (s *Semaphore) Do(ctx context.Context, fn func() error) error

Do 等权便捷方法:获取 1 个单位 → 执行 fn → 自动释放。等价于 bulkhead 模式。

func (*Semaphore) DoWithCost

func (s *Semaphore) DoWithCost(ctx context.Context, cost int64, fn func() error) error

DoWithCost 加权便捷方法:获取 cost 个单位 → 执行 fn → 自动释放。

func (*Semaphore) InFlight

func (s *Semaphore) InFlight() int64

InFlight 返回当前占用的容量。

func (*Semaphore) Release

func (s *Semaphore) Release(cost int64)

Release 释放 cost 个单位的容量。

func (*Semaphore) TryAcquire

func (s *Semaphore) TryAcquire(cost int64) bool

TryAcquire 非阻塞尝试获取。成功返回 true。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL