Documentation
¶
Overview ¶
Package syncx 提供一组便捷的并发原语(泛型),补齐标准库与 pkg/xgo 之外常被手搓、 又容易写错的模式:
- Map / ForEach:对一批元素并发处理,带并发上限 + 错误聚合(首个出错即取消其余);
- SingleFlight:并发相同 key 的调用去重合并,防缓存击穿/惊群;
- Batcher:攒够 N 条或到时间就 flush,批量写库/推送/调用;
- Debounce / Throttle:事件去抖 / 限频;
- Future / Async:异步跑一个函数,稍后 Await 取结果。
仅依赖标准库与 golang.org/x/sync。
Index ¶
- func Debounce(d time.Duration, fn func()) (call func(), cancel func())
- func ForEach[T any](ctx context.Context, items []T, limit int, fn func(context.Context, T) error) error
- func Map[T, R any](ctx context.Context, items []T, limit int, ...) ([]R, error)
- func Throttle(d time.Duration, fn func()) func()
- type Batcher
- type Future
- type Group
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Debounce ¶
Debounce 返回一个去抖函数 call:每次调用都会把 fn 的执行推迟 d;只有在 d 内不再被调用时 fn 才触发 (即"最后一次调用后静默 d 才执行")。cancel 取消尚未触发的待执行。适合配置热更防抖、搜索联想等。 fn 在独立的 time.AfterFunc goroutine 里执行。
func ForEach ¶
func ForEach[T any](ctx context.Context, items []T, limit int, fn func(context.Context, T) error) error
ForEach 对 items 并发执行 fn(不收集结果),最多 limit 个并发(limit<=0 不限)。 任一出错取消其余并返回首个错误。
Types ¶
type Batcher ¶
type Batcher[T any] struct { // contains filtered or unexported fields }
Batcher 把逐条 Add 的元素攒成批,达到 maxSize 条或距上批首条满 maxWait 时,调用 flush 处理一批。 适合批量写库 / 批量推送 / 批量调用。单后台 goroutine 收集,Add 并发安全。零值不可用,用 NewBatcher 构造。
func NewBatcher ¶
NewBatcher 创建批处理器。maxSize>0 为批容量上限,maxWait>0 为一批的最大等待时长(到点即使不满也 flush)。 flush 在后台 goroutine 串行调用,收到的 slice 仅在本次调用内有效(下一批会复用底层数组前不会重叠, 但调用方若需长期持有请自行拷贝)。
type Future ¶
type Future[T any] struct { // contains filtered or unexported fields }
Future 是一个异步计算的结果句柄。用 Async 发起,Await 取结果。