golang-concurrency by samber/cc-skills-golang
npx skills add https://github.com/samber/cc-skills-golang --skill golang-concurrency角色: 你是一名 Go 并发工程师。你默认每个 goroutine 都是潜在的负担,除非证明其必要性——正确性和避免泄漏优先于性能。
模式:
社区默认。 明确覆盖
samber/cc-skills-golang@golang-concurrency技能的公司技能具有优先权。
Go 的并发模型建立在 goroutine 和 channel 之上。Goroutine 廉价但并非免费——你创建的每个 goroutine 都是你必须管理的资源。目标是实现结构化并发:每个 goroutine 都有明确的所有者、可预测的退出方式以及正确的错误传播。
chan<-, <-chan) — 编译器在构建时防止误用广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
ctx.Done() — 没有它,调用者取消后 goroutine 会泄漏time.After — 每次调用都会创建一个定时器,该定时器会一直存活直到触发,导致内存累积。使用 time.NewTimer + Resetgo.uber.org/goleak 追踪 goroutine 泄漏关于 channel/select 代码的详细示例,请参阅 Channels and Select Patterns。
| 场景 | 使用 | 原因 |
|---|---|---|
| 在 goroutine 之间传递数据 | Channel | 传达所有权转移 |
| 协调 goroutine 生命周期 | Channel + context | 通过 select 实现干净的关闭 |
| 保护共享结构体字段 | sync.Mutex / sync.RWMutex | 简单的临界区 |
| 简单的计数器、标志 | sync/atomic | 无锁,开销更低 |
| 对 map 进行大量读、少量写 | sync.Map | 针对读多写少场景优化。并发 map 读/写会导致硬崩溃 |
| 缓存昂贵计算 | sync.Once / singleflight | 执行一次或去重 |
| 需求 | 使用 | 原因 |
|---|---|---|
| 等待 goroutine,无需错误 | sync.WaitGroup | 发射后不管 |
| 等待 + 收集第一个错误 | errgroup.Group | 错误传播 |
| 等待 + 在第一个错误时取消兄弟 goroutine | errgroup.WithContext | 错误时取消上下文 |
| 等待 + 限制并发数 | errgroup.SetLimit(n) | 内置工作池 |
| 原语 | 使用场景 | 关键要点 |
|---|---|---|
sync.Mutex | 保护共享状态 | 保持临界区简短;切勿在 I/O 操作期间持有 |
sync.RWMutex | 大量读,少量写 | 切勿将 RLock 升级为 Lock(会导致死锁) |
sync/atomic | 简单计数器、标志 | 优先使用类型化原子操作(Go 1.19+):atomic.Int64, atomic.Bool |
sync.Map | 并发 map,读多写少 | 无需显式加锁;写操作占主导时使用 RWMutex+map |
sync.Pool | 重用临时对象 | 在 Put() 之前总是 Reset();减少 GC 压力 |
sync.Once | 一次性初始化 | Go 1.21+: OnceFunc, OnceValue, OnceValues |
sync.WaitGroup | 等待 goroutine 完成 | 在 go 之前调用 Add;Go 1.24+: wg.Go() 简化了使用 |
x/sync/singleflight | 对并发调用去重 | 防止缓存击穿 |
x/sync/errgroup | Goroutine 组 + 错误 | SetLimit(n) 替代手动实现的工作池 |
关于详细示例和反模式,请参阅 Sync Primitives Deep Dive。
在创建 goroutine 之前,回答以下问题:
context.Context 或 done channelsync.WaitGroup 或 errgroup关于管道模式(扇出/扇入、有界工作池、生成器链、Go 1.23+ 迭代器、samber/ro),请参阅 Pipelines and Worker Pools。
当审计大型代码库中的并发问题时,最多使用 5 个并行子代理(Agent 工具):
go func, go method)并验证其关闭机制time.After、select 中缺失的 ctx.Done()、无限制的 goroutine 创建sync.Map、原子操作以及线程安全文档| 错误 | 修复方法 |
|---|---|
| 发射后不管的 goroutine | 提供停止机制(context, done channel) |
| 从接收者端关闭 channel | 只有发送者可以关闭 |
在热循环中使用 time.After | 重用 time.NewTimer + Reset |
select 中缺失 ctx.Done() | 总是 select 上下文以允许取消 |
| 无限制地创建 goroutine | 使用 errgroup.SetLimit(n) 或信号量 |
| 通过 channel 共享指针 | 发送副本或不可变值 |
在 goroutine 内部调用 wg.Add | 在 go 之前调用 Add — 否则 Wait 可能提前返回 |
在 CI 中忘记 -race | 总是运行 go test -race ./... |
| 在 I/O 操作期间持有互斥锁 | 保持临界区简短 |
samber/cc-skills-golang@golang-performance 技能,了解伪共享、缓存行填充、sync.Pool 热路径模式samber/cc-skills-golang@golang-context 技能,了解取消传播和超时模式samber/cc-skills-golang@golang-safety 技能,了解并发 map 访问和竞态条件预防samber/cc-skills-golang@golang-troubleshooting 技能,了解调试 goroutine 泄漏和死锁samber/cc-skills-golang@golang-design-patterns 技能,了解优雅关闭模式每周安装量
97
代码仓库
GitHub Stars
184
首次出现
3 天前
安全审计
安装于
opencode79
codex78
gemini-cli78
kimi-cli77
github-copilot77
amp77
Persona: You are a Go concurrency engineer. You assume every goroutine is a liability until proven necessary — correctness and leak-freedom come before performance.
Modes:
Community default. A company skill that explicitly supersedes
samber/cc-skills-golang@golang-concurrencyskill takes precedence.
Go's concurrency model is built on goroutines and channels. Goroutines are cheap but not free — every goroutine you spawn is a resource you must manage. The goal is structured concurrency: every goroutine has a clear owner, a predictable exit, and proper error propagation.
chan<-, <-chan) — the compiler prevents misuse at build timectx.Done() in select — without it, goroutines leak after caller cancellationtime.After in loops — each call creates a timer that lives until it fires, accumulating memory. Use time.NewTimer + Resetgo.uber.org/goleakFor detailed channel/select code examples, see Channels and Select Patterns.
| Scenario | Use | Why |
|---|---|---|
| Passing data between goroutines | Channel | Communicates ownership transfer |
| Coordinating goroutine lifecycle | Channel + context | Clean shutdown with select |
| Protecting shared struct fields | sync.Mutex / sync.RWMutex | Simple critical sections |
| Simple counters, flags | sync/atomic | Lock-free, lower overhead |
| Many readers, few writers on a map | sync.Map | Optimized for read-heavy workloads. Concurrent map read/write causes a hard crash |
| Need | Use | Why |
|---|---|---|
| Wait for goroutines, errors not needed | sync.WaitGroup | Fire-and-forget |
| Wait + collect first error | errgroup.Group | Error propagation |
| Wait + cancel siblings on first error | errgroup.WithContext | Context cancellation on error |
| Wait + limit concurrency | errgroup.SetLimit(n) | Built-in worker pool |
| Primitive | Use case | Key notes |
|---|---|---|
sync.Mutex | Protect shared state | Keep critical sections short; never hold across I/O |
sync.RWMutex | Many readers, few writers | Never upgrade RLock to Lock (deadlock) |
sync/atomic | Simple counters, flags | Prefer typed atomics (Go 1.19+): atomic.Int64, atomic.Bool |
sync.Map | Concurrent map, read-heavy |
For detailed examples and anti-patterns, see Sync Primitives Deep Dive.
Before spawning a goroutine, answer:
context.Context or done channelsync.WaitGroup or errgroupFor pipeline patterns (fan-out/fan-in, bounded workers, generator chains, Go 1.23+ iterators, samber/ro), see Pipelines and Worker Pools.
When auditing concurrency across a large codebase, use up to 5 parallel sub-agents (Agent tool):
go func, go method) and verify shutdown mechanismstime.After in loops, missing ctx.Done() in select, unbounded spawningsync.Map, atomics, and thread-safety documentation| Mistake | Fix |
|---|---|
| Fire-and-forget goroutine | Provide stop mechanism (context, done channel) |
| Closing channel from receiver | Only the sender closes |
time.After in hot loop | Reuse time.NewTimer + Reset |
Missing ctx.Done() in select | Always select on context to allow cancellation |
| Unbounded goroutine spawning | Use errgroup.SetLimit(n) or semaphore |
| Sharing pointer via channel | Send copies or immutable values |
| inside goroutine |
samber/cc-skills-golang@golang-performance skill for false sharing, cache-line padding, sync.Pool hot-path patternssamber/cc-skills-golang@golang-context skill for cancellation propagation and timeout patternssamber/cc-skills-golang@golang-safety skill for concurrent map access and race condition preventionsamber/cc-skills-golang@golang-troubleshooting skill for debugging goroutine leaks and deadlockssamber/cc-skills-golang@golang-design-patterns skill for graceful shutdown patternsWeekly Installs
97
Repository
GitHub Stars
184
First Seen
3 days ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode79
codex78
gemini-cli78
kimi-cli77
github-copilot77
amp77
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
116,600 周安装
Kubernetes专家技能:容器编排、集群管理、生产部署与云原生架构优化指南
96 周安装
Base技能包:bankrbot开源AI助手核心技能库,提升开发效率与代码质量
96 周安装
Capacitor应用调试指南:iOS/Android WebView与原生代码调试完整教程
96 周安装
Nansen 退出信号分析工具:监控聪明资金流向,预警代币风险
96 周安装
Nansen Web Fetcher:基于Gemini AI的网页内容抓取与分析CLI工具
96 周安装
EachLabs Fashion AI:AI时尚模特生成与虚拟试穿API,打造时尚视觉内容
96 周安装
| Caching expensive computations | sync.Once / singleflight | Execute once or deduplicate |
No explicit locking; use RWMutex+map when writes dominate |
sync.Pool | Reuse temporary objects | Always Reset() before Put(); reduces GC pressure |
sync.Once | One-time initialization | Go 1.21+: OnceFunc, OnceValue, OnceValues |
sync.WaitGroup | Wait for goroutine completion | Add before go; Go 1.24+: wg.Go() simplifies usage |
x/sync/singleflight | Deduplicate concurrent calls | Cache stampede prevention |
x/sync/errgroup | Goroutine group + errors | SetLimit(n) replaces hand-rolled worker pools |
wg.AddCall Add before go — Wait may return early otherwise |
Forgetting -race in CI | Always run go test -race ./... |
| Mutex held across I/O | Keep critical sections short |