Go Concurrency Reviewのロゴ

Go Concurrency Review

コミュニティ
eduardo-sl
go-concurrency-review

Review and implement safe concurrency patterns in Go: goroutines, channels, sync primitives, context propagation, and goroutine lifecycle management. Use when writing concurrent code, reviewing async patterns, checking thread safety, debugging race conditions, or designing producer/consumer pipelines. Trigger examples: "check thread safety", "review goroutines", "race condition", "channel patterns", "sync.Mutex", "context cancellation", "goroutine leak". Not for: general style (go-coding-standards), HTTP handler patterns (go-api-design).

概要

公開者eduardo-sl
リポジトリgo-agent-skills
スキル名go-concurrency-review
スター
86
フォーク
11
同梱ファイル
3
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 3個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    eduardo-slがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Go Concurrency Review」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/eduardo-sl/go-agent-skills/tree/main/skills/(safety)/go-concurrency-review
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。

TypingMindで使用

TypingMindのチャットでGo Concurrency Reviewを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にGo Concurrency Reviewを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Go Concurrency Reviewは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

Go Concurrency Review

Concurrency in Go is powerful and deceptively easy to get wrong. These patterns prevent goroutine leaks, data races, and deadlocks.

Detailed reference material, loaded on demand:

  • references/channels.md — sizing, signalling, producer shutdown.
  • references/mutex-and-atomics.md — mutex placement, lock scope, atomics, sync.Once, RWMutex pitfalls, sync.Map, sync.Pool, singleflight.
  • references/goroutine-patterns.md — panic recovery at goroutine boundaries, pipelines, bounded fan-out, timers.

Read a reference file only when the section below is not enough.

Operating Modes

Pick the mode that matches the request before starting:

  • Implementation — writing new concurrent code. Follow the patterns below as construction rules.
  • Diff review (default) — check changed code against every section, paying extra attention to new go statements and shared state.
  • Leak/race hunt — a symptom is already observed (growing goroutine count, -race report, deadlock). Start from "Auditing Large Codebases" and the Race Detection section to localize it. On Go 1.27+ read the goroutineleak profile first: it lists goroutines blocked on something nothing can ever unblock. The go-troubleshooting skill owns the procedure.

Auditing Large Codebases

For a full concurrency audit, run these independent passes rather than one linear read:

  1. Goroutine lifecycle: find every go statement (grep -rn "go func\|go [a-zA-Z]" --include="*.go") and verify each has a termination path (context, closed channel, WaitGroup).
  2. Shared state: find package-level vars and struct fields accessed from multiple goroutines; verify mutex/atomic protection.
  3. Channel topology: map producers/consumers per channel; verify close-exactly-once and no send-on-closed paths.
  4. Context propagation: verify blocking calls accept and respect context.Context.

If your environment supports delegating work to parallel sub-agents or tasks, assign each pass to one; otherwise run them in order. Findings must cite file.go:line. Always finish with go test -race ./....

Choosing a Primitive

NeedUseWhy
Hand data from one goroutine to anotherChannelThe send transfers ownership
Guard fields of a shared structsync.Mutex / RWMutexShort critical sections, explicit owner
A counter or flagatomic.Int64, atomic.BoolNo lock, no torn reads
Compute once, read manysync.OnceValueExactly once, even under contention
Collapse concurrent identical callssingleflight.GroupOne backend call per key, not N
Reuse short-lived buffers on a hot pathsync.PoolFewer allocations — only after a profile
Waiting for goroutinesUse
Results don't failsync.WaitGroup (wg.Go, Go 1.25+)
First error matterserrgroup.Group
First error cancels the resterrgroup.WithContext
Cap how many run at onceerrgroup + SetLimit(n) — not a hand-rolled pool

1. Goroutine Lifecycle Management

EVERY goroutine MUST have a clear termination path. No fire-and-forget.

Use errgroup for coordinated goroutines:

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

g.Go(func() error {
    return fetchUsers(ctx)
})

g.Go(func() error {
    return fetchOrders(ctx)
})

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

Long-running goroutines must respect context:

go
func (w *Worker) Run(ctx context.Context) error {
    for {
        select {
        case <-ctx.Done():
            return ctx.Err()
        case job := <-w.jobs:
            if err := w.process(job); err != nil {
                w.logger.Error("process job", slog.Any("error", err))
            }
        }
    }
}

Start goroutines in the owner, not the callee:

go
// ✅ Good — caller controls lifecycle
go worker.Run(ctx)

// ❌ Bad — function secretly starts goroutine
func NewWorker() *Worker {
    w := &Worker{}
    go w.run() // hidden goroutine — caller has no control
    return w
}

Recover at the goroutine boundary

A panic in any goroutine terminates the whole process. The recover in HTTP middleware covers the request goroutine only, not goroutines it starts. Workers and background tasks that run input-dependent or third-party code recover in their own deferred function, log the stack, and turn the panic into an error. Don't recover to hide bugs in code you own — recover where a crash would take unrelated work down with it. Example: references/goroutine-patterns.md.

2. Channel Patterns

  • Size is one or none. Unbuffered is a synchronization point; buffer 1 is a handoff. Any larger buffer needs a comment justifying the number — an arbitrary 100 is a bug waiting for the day production is slower than staging.

  • Signal channels carry struct{}, and close(done) broadcasts to every receiver at once.

  • The producer owns the channel and is the only one that closes it, with defer close(ch) in the producing goroutine. Every send sits in a select against ctx.Done(), or a consumer that walks away leaks the producer.

  • Pipelines: each stage closes its own output; fan-out is bounded with errgroup.SetLimit; a single-goroutine chain is an iter.Seq, not channels.

Examples in references/channels.md and references/goroutine-patterns.md.

3. Mutexes and Atomics

  • Zero-value sync.Mutex and sync.RWMutex are ready to use. A *sync.Mutex field is always wrong.
  • Declare the mutex directly above the fields it guards, with a comment naming the relationship. A mutex that guards "the struct" guards nothing in particular.
  • Keep the critical section minimal — never call out to an external service, or take a second lock, while holding one.
  • 🔴 Never copy a value containing a mutex (c2 := *c1): the copy carries the original's lock state. go vet catches most of these; trust it.
  • Use sync/atomic types for counters and flags rather than a mutex around an int64.
  • sync.Once for lazy initialization that must happen exactly once.
  • RWMutex cannot be upgraded or read-locked recursively; sync.Map fits two workloads only; sync.Pool objects must be reset and size-capped; singleflight runs on the first caller's context — detach it. Details in references/mutex-and-atomics.md.

Examples in references/mutex-and-atomics.md.

4. Context Propagation

Context is always the first parameter, never a struct field, and every blocking operation selects on ctx.Done():

go
// ✅ Good
select {
case result := <-ch:
    return result, nil
case <-ctx.Done():
    return nil, ctx.Err()
}

// ❌ Bad — blocks forever if the context is cancelled
result := <-ch

Derive a child context with its own timeout for each external call and defer cancel() immediately. Full rules in the go-context skill.

5. Avoid Mutable Globals

go
// ❌ Bad — mutable global, not safe for concurrent access
var db *sql.DB

// ✅ Good — pass as dependency
type Server struct {
    db *sql.DB
}

Race Detection

ALWAYS run tests with race detector during CI:

bash
go test -race ./...

This is non-negotiable. A test suite that passes without -race proves nothing about concurrent correctness.

Red Flags Checklist

  • 🔴 Goroutine started without shutdown path
  • 🔴 Channel never closed (potential goroutine leak)
  • 🔴 Mutex copied by value
  • 🔴 Context stored in struct field
  • 🔴 context.Background() used where parent context was available
  • 🔴 select without ctx.Done() case in blocking operation
  • 🔴 Shared map/slice accessed without synchronization
  • 🟡 Buffered channel with arbitrary large size
  • 🟡 time.Sleep used for synchronization instead of proper signaling
  • 🟡 Goroutine starting inside init() or constructor without lifecycle control
  • 🟡 Background goroutine running input-dependent code with no recover

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「Go Concurrency Review」では何ができますか?

Review and implement safe concurrency patterns in Go: goroutines, channels, sync primitives, context propagation, and goroutine lifecycle management. Use when writing concurrent code, reviewing async patterns, checking thread safety, debugging race conditions, or designing producer/consumer pipelines. Trigger examples: "check thread safety", "review goroutines", "race condition", "channel patterns", "sync.Mutex", "context cancellation", "goroutine leak". Not for: general style (go-coding-standards), HTTP handler patterns (go-api-design).

TypingMindでGo Concurrency Reviewを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Go Concurrency Reviewはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにGo Concurrency Reviewをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/eduardo-sl/go-agent-skills/tree/main/skills/(safety)/go-concurrency-reviewを貼り付けてください。TypingMindがSKILL.mdを読み込み、関連ファイルをまとめて、チャットごとに有効にできるスキルとしてインストールします。

Go Concurrency Reviewを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Go Concurrency Reviewで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもGo Concurrency Reviewを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Go Concurrency Review」は無料ですか?

はい。eduardo-slがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇