group

package
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package group 提供并发 Actor 生命周期管理和 WaitGroup 封装。

  • Group: Actor 模式,第一个返回的函数会中断所有其他 Actor
  • WaitGroupWrapper: context 感知的 WaitGroup,支持 panic 恢复和错误传播

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Group

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

Group 收集多个 Actor(函数对)并并发执行。 当任意一个 Actor 返回时,所有其他 Actor 通过 interrupt 函数被中断。 零值可用。

典型用法:用于管理多个长期运行的 goroutine(HTTP server、gRPC server、信号监听等), 确保其中一个退出时,其他全部被通知停止。

g := &group.Group{}
g.Add(func() error { return httpServer.ListenAndServe() }, func(error) { httpServer.Close() })
g.Add(func() error { return grpcServer.Serve() }, func(error) { grpcServer.GracefulStop() })
g.Add(func() error { <-ctx.Done(); return nil }, func(error) {})
err := g.Run()

func (*Group) Add

func (g *Group) Add(execute func() error, interrupt func(error))

Add 注册一个 Actor(execute + interrupt 函数对)。

execute: 实际执行的函数,应在 interrupt 被调用时返回。 interrupt: 通知 execute 停止的函数,即使 execute 已返回也必须安全可调用。

func (*Group) Run

func (g *Group) Run() error

Run 并发执行所有 Actor。 当第一个 Actor 返回时,其 error 传递给所有其他 Actor 的 interrupt 函数。 Run 阻塞直到所有 Actor 退出,返回第一个退出的 Actor 的 error。

type RunOption

type RunOption func(opts *runOptions)

RunOption 配置 WaitGroupWrapper 的可选参数。

func WithTimeout

func WithTimeout(timeout time.Duration) RunOption

WithTimeout 为 WaitGroup 的 context 设置超时。

type WaitGroupWrapper

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

WaitGroupWrapper 是 context 感知的 WaitGroup 封装。

特性:

  • 每个 goroutine 携带 context(支持超时/取消)
  • panic 自动恢复并转换为 error(不会把 panic 当成成功)
  • 第一个 error 自动取消 context(级联取消兄弟 goroutine)
  • Wait() 返回第一个 error

用法:

wg := group.NewWaitGroup(ctx)
wg.Wrap(func(ctx context.Context) error { return doWork(ctx) })
wg.Wrap(func(ctx context.Context) error { return doMore(ctx) })
if err := wg.Wait(); err != nil { ... }

func NewWaitGroup

func NewWaitGroup(ctx context.Context, opts ...RunOption) *WaitGroupWrapper

NewWaitGroup 创建一个 WaitGroupWrapper。 ctx 为父 context,支持通过 WithTimeout 设置全局超时。

func (*WaitGroupWrapper) Wait

func (w *WaitGroupWrapper) Wait() error

Wait 阻塞直到所有 Wrap 启动的 goroutine 退出。 返回第一个非 nil error,如果全部成功则返回 nil。

func (*WaitGroupWrapper) Wrap

func (w *WaitGroupWrapper) Wrap(cb func(ctx context.Context) error)

Wrap 启动一个被追踪的 goroutine。 goroutine 会继承 WaitGroup 的 context。 如果 cb 返回非 nil error 或发生 panic,context 会被取消(影响其他兄弟 goroutine), panic 会被转换为 error 并通过 Wait 返回(不会丢失或被当成成功)。

Jump to

Keyboard shortcuts

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