AgentSkillsCN

concurrency

掌握 Goroutine 所有权、errgroup 模式、工作池,以及优雅关闭机制。适用于编写并发代码或并行处理请求时使用。

SKILL.md
--- frontmatter
name: concurrency
description: Goroutine ownership, errgroup patterns, worker pools, and graceful shutdown. Use when writing concurrent code or parallel request handling.
userInvokable: true

Concurrency

References: Examples

Core Rule

No fire-and-forget goroutines. Every goroutine must have managed lifecycle.

RequirementDescription
Context cancellationPass ctx and respect ctx.Done() for graceful shutdown
SynchronizationUse sync.WaitGroup or errgroup.Group to wait for completion
Bounded concurrencyLimit parallel goroutines with semaphore or worker pool
Error propagationUse errgroup when errors need to bubble up
Parallel requestsAlways use errgroup for parallel HTTP/DB/API calls

Pattern Selection

PatternUse When
sync.WaitGroupSimple fan-out, no error collection needed
errgroup.GroupNeed first error, automatic cancellation
errgroup.SetLimit(n)Bounded concurrency with error handling
Worker poolHigh-volume processing, backpressure needed

Do / Don't

DoDon't
errgroup.Group with contextgo func() { process() }()
Worker pool with fixed sizeUnbounded for { go handle() }
select on ctx.Done()Ignore cancellation signals
Explicit wg.Wait()Hope goroutines finish

errgroup for Parallel Requests

Example

go
g, ctx := errgroup.WithContext(ctx)

g.Go(func() error { return fetchA(ctx) })
g.Go(func() error { return fetchB(ctx) })
g.Go(func() error { return fetchC(ctx) })

if err := g.Wait(); err != nil {
    return fmt.Errorf("parallel fetch: %w", err)
}

Bounded Concurrency

Example

go
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(10)  // Max 10 concurrent goroutines

for _, item := range items {
    item := item
    g.Go(func() error { return process(ctx, item) })
}

return g.Wait()

Worker Pool

Example

For high-volume processing with backpressure control.

Graceful Shutdown

Example

Always handle context cancellation in long-running goroutines.