Token导航 LogoToken导航TokenDH.com
运维和基础设施需要联网github未标认证来源可访问clear审计通过

golang-concurrency-patternsGo concurrency 模式

Agent Skill

golang-concurrency-patterns 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

5,239

周安装

214

GitHub Stars

40

下载量

1,695
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:golang-concurrency-patterns(Go concurrency 模式)
来源仓库:https://github.com/bobmatnyc/claude-mpm-skills
仓库路径:skills/golang-concurrency-patterns
安装命令:
npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill golang-concurrency-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill golang-concurrency-patterns

简介

golang-concurrency-patterns 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中围绕仓库状态、代码变更或协作事项进行整理。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装并使用。
  • 安装前需确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Go Concurrency Patterns (Production)

Overview

Go concurrency scales when goroutine lifetimes are explicit, cancellation is propagated with context.Context, and shared state is protected (channels or locks). Apply these patterns to build reliable services and avoid common failure modes: goroutine leaks, deadlocks, and data races.

Quick Start

Default building blocks

  • Use context to drive cancellation and deadlines.
  • Use errgroup.WithContext for fan-out/fan-in with early abort.
  • Bound concurrency (avoid unbounded goroutines) with a semaphore or worker pool.
  • Prefer immutable data; otherwise protect shared state with a mutex or make a single goroutine the owner.

Avoid

  • Fire-and-forget goroutines in request handlers.
  • time.After inside hot loops.
  • Closing channels from the receiver side.
  • Sharing mutable variables across goroutines without synchronization.

Core Concepts

Goroutine lifecycle

Treat goroutines as resources with a clear owner and shutdown condition.

Correct: stop goroutines via context

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go func() {
    ticker := time.NewTicker(250 * time.Millisecond)
    defer ticker.Stop()

    for {
        select {
        case <-ctx.Done():
            return
        case <-ticker.C:
            // do work
        }
    }
}()

Wrong: goroutine without a stop condition

go func() {
    for {
        doWork() // leaks forever
    }
}()

Channels vs mutexes (choose intentionally)

  • Use channels to model ownership/serialization of state or to pipeline work.
  • Use mutexes to protect shared in-memory state with simple read/write patterns.

Correct: one goroutine owns the map

type req struct {
    key   string
    reply chan<- int
}

func mapOwner(ctx context.Context, in <-chan req) {
    m := map[string]int{}
    for {
        select {
        case <-ctx.Done():
            return
        case r := <-in:
            r.reply <- m[r.key]
        }
    }
}

Correct: mutex protects shared map

type SafeMap struct {
    mu sync.RWMutex
    m  map[string]int
}

func (s *SafeMap) Get(k string) (int, bool) {
    s.mu.RLock()
    defer s.mu.RUnlock()
    v, ok := s.m[k]
    return v, ok
}

Patterns

1) Fan-out/fan-in with cancellation (errgroup)

Use errgroup.WithContext to run concurrent tasks, cancel siblings on error, and wait for completion.

Correct: cancel on first error

g, ctx := errgroup.WithContext(ctx)

for _, id := range ids {
    id := id // capture
    g.Go(func() error {
        return process(ctx, id)
    })
}

if err := g.Wait(); err != nil {
    return err
}

Wrong: WaitGroup loses the first error and does not propagate cancellation

var wg sync.WaitGroup
for _, id := range ids {
    wg.Add(1)
    go func() {
        defer wg.Done()
        _ = process(context.Background(), id) // ignores caller ctx + captures id
    }()
}
wg.Wait()

2) Bounded concurrency (semaphore pattern)

Bound parallelism to prevent CPU/memory exhaustion and downstream overload.

Correct: bounded fan-out

limit := make(chan struct{}, 8) // max 8 concurrent
g, ctx := errgroup.WithContext(ctx)

for _, id := range ids {
    id := id
    g.Go(func() error {
        select {
        case <-ctx.Done():
            return ctx.Err()
        case limit <- struct{}{}:
        }
        defer func() { <-limit }()

        return process(ctx, id)
    })
}

return g.Wait()

3) Worker pool (durable throughput)

Use a fixed number of workers for stable throughput and predictable resource usage.

Correct: worker pool with context stop

type Job struct{ ID string }

func runPool(ctx context.Context, jobs <-chan Job, workers int) error {
    g, ctx := errgroup.WithContext(ctx)

    for i := 0; i < workers; i++ {
        g.Go(func() error {
            for {
                select {
                case <-ctx.Done():
                    return ctx.Err()
                case j, ok := <-jobs:
                    if !ok {
                        return nil
                    }
                    if err := handleJob(ctx, j); err != nil {
                        return err
                    }
                }
            }
        })
    }

    return g.Wait()
}

4) Pipeline stages (fan-out between stages)

Prefer one-directional channels and close only from the sending side.

Correct: sender closes

func stageA(ctx context.Context, out chan<- int) {
    defer close(out)
    for i := 0; i < 10; i++ {
        select {
        case <-ctx.Done():
            return
        case out <- i:
        }
    }
}

Wrong: receiver closes

func stageB(in <-chan int) {
    close(in) // compile error in<-chan; also wrong ownership model
}

5) Periodic work without leaks (time.Ticker vs time.After)

Use time.NewTicker for loops; avoid time.After allocations in hot paths.

Correct: ticker

t := time.NewTicker(1 * time.Second)
defer t.Stop()

for {
    select {
    case <-ctx.Done():
        return
    case <-t.C:
        poll()
    }
}

Wrong: time.After in loop

for {
    select {
    case <-ctx.Done():
        return
    case <-time.After(1 * time.Second):
        poll()
    }
}

Decision Trees

Channel vs Mutex

  • Need ownership/serialization (single writer, message passing) → use channel + owner goroutine
  • Need shared cache/map with many readers and simple updates → use RWMutex
  • Need simple counter with low contention → use atomic

WaitGroup vs errgroup

  • Need error propagation + sibling cancellation → use errgroup.WithContext
  • Need only wait and errors are handled elsewhere → use sync.WaitGroup

Buffered vs unbuffered channel

  • Need backpressure and synchronous handoff → use unbuffered
  • Need burst absorption up to a known size → use buffered (size with intent)
  • Unsure → start unbuffered and measure; add buffer only to remove known bottleneck

Testing & Verification

Race detector and flake control

Run targeted tests with the race detector and disable caching during debugging:

go test -race ./...
go test -run TestName -race -count=1 ./...

Timeouts to prevent hanging tests

Correct: test-level timeout via context

func TestSomething(t *testing.T) {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()

    if err := doThing(ctx); err != nil {
        t.Fatal(err)
    }
}

Troubleshooting

Symptom: deadlock (test hangs, goroutines blocked)

Actions:

  • Add timeouts (context.WithTimeout) around blocking operations.
  • Verify channel ownership: only the sender closes; receivers stop on ok == false.
  • Check for missing <-limit release in semaphore patterns.

Symptom: data race (go test -race reports)

Actions:

  • Identify shared variables mutated by multiple goroutines.
  • Add a mutex or convert to ownership model (single goroutine owns state).
  • Avoid writing to captured loop variables.

Symptom: goroutine leak (memory growth, slow shutdown)

Actions:

  • Ensure every goroutine selects on ctx.Done().
  • Ensure time.Ticker is stopped and channels are closed by senders.
  • Avoid context.Background() inside request paths; propagate caller context.

Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

33.19%
按下载量换算563

OpenCode

24.44%
按下载量换算414

Gemini CLI

17.45%
按下载量换算296

Antigravity

12.6%
按下载量换算214

github-copilot

8.07%
按下载量换算137

Codex

3.18%
按下载量换算54

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills