К основному содержанию
скилл CX Codex

go-concurrency — скилл для Claude Code: конкурентность в Go

Правила для горутин, каналов и мьютексов, чтобы агент не плодил утечки и гонки данных в Go-коде.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add cxuu/golang-skills --skill go-concurrency -a claude-code
Открыть на GitHub

Что делает go-concurrency

Скилл включается, когда вы пишете или правите конкурентный код на Go: горутины, каналы, мьютексы, атомики, защита общего состояния. Агент получает набор нормативных правил: у каждой горутины должен быть способ остановки, код обязан уметь дождаться её завершения, а запуск горутин в init() запрещён — вместо этого нужны методы жизненного цикла вроде Close и Shutdown.

Внутри четыре справочника, которые агент читает по ситуации: references/GOROUTINE-PATTERNS.md про запуск и ожидание горутин, references/SYNC-PRIMITIVES.md про выбор между мьютексом, атомиком и каналом, references/BUFFER-POOLING.md про переиспользование буферов, references/ADVANCED-PATTERNS.md про worker pools, пайплайны и errgroup. Отдельно оговорены размеры каналов: ноль или один, всё остальное требует обоснования.

Тему context.Context скилл не разбирает — её отдают соседнему go-context, так что при работе с отменой и дедлайнами ждите переключения на другой скилл. В примерах с атомиками возможны типизированные атомики из стандартной библиотеки или go.uber.org/atomic, если проект уже от него зависит. Для проверки утечек горутин в тестах упоминается go.uber.org/goleak.

Какие задачи решает

  • запустить горутины и дождаться их завершения через sync.WaitGroup
  • выбрать между мьютексом, атомиком и каналом для общего состояния
  • починить гонку данных на общем счётчике или кэше
  • собрать worker pool или пайплайн с errgroup
  • найти утечку горутины в тестах

Примеры запросов агенту

  • Перепиши этот цикл на горутины с WaitGroup и объясни, как они останавливаются
  • Здесь гонка на счётчике — выбери примитив синхронизации и покажи правку
  • Собери worker pool для обработки очереди задач

Как установить go-concurrency

1Через Skills CLI (Vercel)

npx skills add cxuu/golang-skills --skill go-concurrency -a claude-code

2Вручную: положить файлы

~/.claude/skills/go-concurrency/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/go-concurrency/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора19

go-code-review Проверяет Go-код по общепринятым стандартам стиля и выдаёт замечания по severity. Пригодится перед отправкой PR. CX Codex +1 1 700установок go-documentation Пишет и проверяет доккомментарии для экспортируемых типов, функций и пакетов Go. Срабатывает и сам, когда вы создаёте новый экспортируемый API. CX Codex +1 1 300установок go-error-handling Скилл учит агента писать надёжную обработку ошибок в Go: выбирать между %w и %v, задавать sentinel-ошибки и не смешивать логирование с возвратом. CX Codex +1 1 300установок go-testing Скилл для написания и разбора тестов на Go: table-driven тесты, сабтесты, хелперы и сравнение через cmp.Diff. Пригодится, когда агент пишет тест к функции. CX Codex +1 1 300установок go-control-flow Скилл учит агента писать канонические циклы, ветвления и switch в Go. Пригодится при оформлении guard clauses и предотвращении багов с затенением переменных. CX Codex +1 1 200установок go-functional-options Скилл подсказывает, как собрать конструктор в Go с необязательными настройками через функциональные опции. Пригодится, когда у New* уже три и больше необязательных параметров. CX Codex +1 1 200установок go-data-structures Скилл для ИИ-агента, который подсказывает идиомы Go при работе со срезами, картами и массивами: make против new, append, nil-срезы и JSON. CX Codex +1 1 200установок go-packages Задаёт правила разбиения Go-кода на пакеты, структурирует импорты и запрещает пакеты util. Пригодится на старте проекта или при рефакторинге растущей кодовой базы. CX Codex +1 1 200установок

Похожие

golang-concurrency samber Скилл задаёт правила для конкурентного кода на Go: жизненный цикл горутин, каналы и select, мьютексы, errgroup, singleflight, воркер-пулы и fan-out/fan-in пайплайны. CX Codex +1 41 800установок golang-concurrency-patterns Claude MPM Team Скилл для написания конкурентного Go-кода: отмена через context, errgroup, worker pools и разбор типичных гонок и дедлоков. CX Codex +1 408установок csharp-concurrency-patterns Aaronontheweb Помогает агенту выбирать подходящие абстракции многопоточности в .NET: от async/await до Channels и Akka.NET. Пригодится при проектировании очередей и избавлении от блокировок. CX Codex +1 1 600установок m07-concurrency actionbook Помогает разбирать конкурентный и асинхронный Rust-код: выбрать потоки, async/await, каналы или синхронизацию. Нужен при ошибках Send/Sync, дедлоках и гонках. CX Codex +1 3 500установок asyncio-concurrency-patterns manutej Скилл по конкурентности в Python: event loop, корутины, задачи, семафоры и блокировки. Пригодится, когда пишешь асинхронный сервис или клиент. CX Codex +1 489установок java-concurrency pluginagentmarketplace Скилл для ИИ-агента, который помогает писать потокобезопасный код на Java: от обычных потоков до виртуальных в Java 21+. CX Codex +1 465установок

Рядом в теме «Языки программирования»

Все скиллы по теме «Языки программирования» →

Вопросы о go-concurrency

Как установить go-concurrency в Claude?

Через установщик скиллов: npx skills add cxuu/golang-skills --skill go-concurrency -a claude-code. После этого файл скилла лежит в ~/.claude/skills/go-concurrency/SKILL.md.

Что делает go-concurrency?

Задаёт агенту правила конкурентного кода на Go: время жизни горутин, выбор примитивов синхронизации, направление и размер каналов, документирование потокобезопасности.

Разбирает ли скилл context.Context?

Нет. Отмена, дедлайны и значения из запроса вынесены в отдельный скилл go-context, а этот про горутины, каналы и мьютексы.

Исходный текст

SKILL.md · Apache-2.0
---
name: go-concurrency
description: Use when writing concurrent Go code — goroutines, channels, mutexes, or thread-safety guarantees. Also use when parallelizing work, fixing data races, or protecting shared state, even if the user doesn't explicitly mention concurrency primitives. Does not cover context.Context patterns (see go-context).
---

# Go Concurrency

> Compatibility: Atomic examples may use standard-library typed atomics where available or `go.uber.org/atomic` where a project already depends on it.

## Resource Routing

- `references/GOROUTINE-PATTERNS.md` - Read when starting, stopping, or waiting for goroutines.
- `references/SYNC-PRIMITIVES.md` - Read when choosing between mutexes, atomics, channels, and once-like primitives.
- `references/BUFFER-POOLING.md` - Read when considering channel-backed or sync.Pool-style reuse.
- `references/ADVANCED-PATTERNS.md` - Read for worker pools, pipelines, errgroup, and cancellation-heavy patterns.

## Goroutine Lifetimes

> **Normative**: When you spawn goroutines, make it clear when or whether they
> exit.

Goroutines can leak by blocking on channel sends/receives. The GC **will not
terminate** a blocked goroutine even if no other goroutine holds a reference to
the channel. Even non-leaking in-flight goroutines cause panics (send on closed
channel), data races, memory issues, and resource leaks.

### Core Rules

1. **Every goroutine needs a stop mechanism** — a predictable end time, a
   cancellation signal, or both
2. **Code must be able to wait** for the goroutine to finish
3. **No goroutines in `init()`** — expose lifecycle methods (`Close`, `Stop`,
   `Shutdown`) instead
4. **Keep synchronization scoped** — constrain to function scope, factor logic
   into synchronous functions

```go
// Good: Clear lifetime with WaitGroup.Go (Go 1.25+)
var wg sync.WaitGroup
for item := range queue {
    item := item
    wg.Go(func() { process(ctx, item) })
}
wg.Wait()
```

```go
// Bad: No way to stop or wait
go func() { for { flush(); time.Sleep(delay) } }()
```

**Test for leaks** with [go.uber.org/goleak](https://pkg.go.dev/go.uber.org/goleak).

> **Principle**: Never start a goroutine without knowing how it will stop.

---

## Share by Communicating

> "Do not communicate by sharing memory; instead, share memory by communicating."

This is Go's foundational concurrency design principle. Use **channels** for
ownership transfer and orchestration — when one goroutine produces a value and
another consumes it. Use **mutexes** when multiple goroutines access shared
state and channels would add unnecessary complexity.

**Default to channels.** Fall back to `sync.Mutex` / `sync.RWMutex` when the
problem is naturally about protecting a shared data structure (e.g., a cache or
counter) rather than passing data between goroutines.

---

## Synchronous Functions

> **Normative**: Prefer synchronous functions over asynchronous ones.

| Benefit | Why |
|---|---|
| Localized goroutines | Lifetimes easier to reason about |
| Avoids leaks and races | Easier to prevent resource leaks and data races |
| Easier to test | Check input/output without polling |
| Caller flexibility | Caller adds concurrency when needed |

> **Advisory**: It is quite difficult (sometimes impossible) to remove
> unnecessary concurrency at the caller side. Let the caller add concurrency
> when needed.

---

## Zero-value Mutexes

The zero-value of `sync.Mutex` and `sync.RWMutex` is valid — almost never need
a pointer to a mutex.

```go
// Good: Zero-value is valid    // Bad: Unnecessary pointer
var mu sync.Mutex                mu := new(sync.Mutex)
```

**Don't embed mutexes** — use a named `mu` field to keep `Lock`/`Unlock` as
implementation details, not exported API.

---

## Channel Direction

> **Normative**: Specify channel direction where possible.

Direction prevents errors (compiler catches closing a receive-only channel),
conveys ownership, and is self-documenting.

```go
func produce(out chan<- int) { /* send-only */ }
func consume(in <-chan int)  { /* receive-only */ }
func transform(in <-chan int, out chan<- int) { /* both */ }
```

### Channel Size: One or None

Channels should have size **zero** (unbuffered) or **one**. Any other size
requires justification for:

- How the size was determined
- What prevents the channel from filling under load
- What happens when writers block

```go
c := make(chan int)    // unbuffered — Good
c := make(chan int, 1) // size one — Good
c := make(chan int, 64) // arbitrary — needs justification
```

---

## Atomic Operations

Use `atomic.Bool`, `atomic.Int64`, etc. (stdlib `sync/atomic` since Go 1.19, or
[go.uber.org/atomic](https://pkg.go.dev/go.uber.org/atomic)) for type-safe
atomic operations. Raw `int32`/`int64` fields make it easy to forget atomic
access on some code paths.

```go
// Good: Type-safe              // Bad: Easy to forget
var running atomic.Bool          var running int32 // atomic
running.Store(true)              atomic.StoreInt32(&running, 1)
running.Load()                   running == 1 // race!
```

---

## Documenting Concurrency

> **Advisory**: Document thread-safety when it's not obvious from the operation
> type.

Go users assume read-only operations are safe for concurrent use, and mutating
operations are not. Document concurrency when:

1. **Read vs mutating is unclear** — e.g., a `Lookup` that mutates LRU state
2. **API provides synchronization** — e.g., thread-safe clients
3. **Interface has concurrency requirements** — document in type definition

---

## Context Usage

> For context.Context guidance (parameter placement, struct storage, custom
> types, derivation patterns), see the dedicated
> [go-context](../go-context/SKILL.md) skill.

---

## Buffer Pooling with Channels

Use a buffered channel as a free list to reuse allocated buffers. This "leaky
buffer" pattern uses `select` with `default` for non-blocking operations.

---

## Related Skills

- **Context propagation**: See [go-context](../go-context/SKILL.md) when passing cancellation, deadlines, or request-scoped values through goroutines
- **Error handling**: See [go-error-handling](../go-error-handling/SKILL.md) when propagating errors from goroutines or using errgroup
- **Defensive hardening**: See [go-defensive](../go-defensive/SKILL.md) when protecting shared state at API boundaries or using defer for cleanup
- **Interface design**: See [go-interfaces](../go-interfaces/SKILL.md) when choosing receiver types for types with sync primitives

### External Resources

- [Never start a goroutine without knowing how it will
  stop](https://dave.cheney.net/2016/12/22/never-start-a-goroutine-without-knowing-how-it-will-stop)
  — Dave Cheney
- [Rethinking Classical Concurrency
  Patterns](https://www.youtube.com/watch?v=5zXAHh5tJqQ) — Bryan Mills
  (GopherCon 2018)
- [When Go programs end](https://changelog.com/gotime/165) — Go Time podcast
- [go.uber.org/goleak](https://pkg.go.dev/go.uber.org/goleak) — Goroutine leak
  detector for testing
- [go.uber.org/atomic](https://pkg.go.dev/go.uber.org/atomic) — Type-safe
  atomic operations

© cxuu · Apache-2.0 · cxuu/golang-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой