MCP HubMCP Hub
SKILL·F824BC

go-concurrency-review

eduardo-sl
업데이트됨 22 days ago
5 조회
68
9
68
GitHub에서 보기
테스팅apidesign

정보

이 스킬은 Go 언어의 안전한 동시성 패턴을 검토하고 구현하는 방법을 다루며, 고루틴, 채널, 동기화 기본 요소, 그리고 생명주기 관리에 대해 설명합니다. 동시성 코드 작성, 레이스 컨디션 디버깅, 또는 생산자/소비자 파이프라인 설계 시 사용하세요. 이 스킬은 일반적인 스타일이나 HTTP 핸들러가 아닌, 스레드 안전성과 비동기 패턴에 특별히 초점을 맞춥니다.

빠른 설치

Claude Code

추천
기본
npx skills add eduardo-sl/go-agent-skills -a claude-code
플러그인 명령대체
/plugin add https://github.com/eduardo-sl/go-agent-skills
Git 클론대체
git clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-concurrency-review

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Go Concurrency Review

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

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.

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 ./....

1. Goroutine Lifecycle Management

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

Use errgroup for coordinated goroutines:

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:

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:

// ✅ 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
}

2. Channel Patterns

Channel size is one or none:

// Unbuffered — synchronization point
ch := make(chan Result)

// Buffered with size 1 — single-item handoff
ch := make(chan Result, 1)

// Larger buffers need explicit justification with documented reasoning
ch := make(chan Result, 100) // requires comment explaining why

Signal channels use empty struct:

done := make(chan struct{})
close(done) // broadcast signal to all receivers

Producer/consumer with clean shutdown:

func produce(ctx context.Context) <-chan Item {
    ch := make(chan Item)
    go func() {
        defer close(ch)
        for {
            item, err := fetchNext(ctx)
            if err != nil {
                return
            }
            select {
            case ch <- item:
            case <-ctx.Done():
                return
            }
        }
    }()
    return ch
}

3. Mutex Patterns

Zero-value mutexes are valid:

// ✅ Good — zero value works
type Cache struct {
    mu    sync.RWMutex
    items map[string]Item
}

// ❌ Bad — unnecessary pointer
type Cache struct {
    mu    *sync.RWMutex // never do this
}

Mutex placement in struct:

type SafeMap struct {
    mu sync.RWMutex // mutex guards the fields below
    items map[string]string
    count int
}

The mutex should appear directly above the field(s) it protects, with a comment indicating the relationship.

Lock scope should be minimal:

// ✅ Good — minimal lock scope
func (c *Cache) Get(key string) (Item, bool) {
    c.mu.RLock()
    item, ok := c.items[key]
    c.mu.RUnlock()
    return item, ok
}

// ✅ Also good — defer for methods that return early
func (c *Cache) GetOrCreate(key string) Item {
    c.mu.Lock()
    defer c.mu.Unlock()

    if item, ok := c.items[key]; ok {
        return item
    }
    item := newItem(key)
    c.items[key] = item
    return item
}

Never copy mutexes:

// ❌ BLOCKER — copying a mutex copies its lock state
cache2 := *cache1 // this copies the mutex!

4. Atomic Operations

Use sync/atomic or go.uber.org/atomic for simple counters and flags:

// ✅ Good — type-safe atomics
import "go.uber.org/atomic"

type Server struct {
    running atomic.Bool
    reqCount atomic.Int64
}

func (s *Server) HandleRequest() {
    s.reqCount.Inc()
    // ...
}

5. Context Propagation

Rules:

  • Context is ALWAYS the first parameter.
  • Never store context in a struct field.
  • Derive child contexts for sub-operations:
func (s *Service) Process(ctx context.Context, req Request) error {
    // Derive context with timeout for external call
    fetchCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel() // ALWAYS defer cancel

    data, err := s.client.Fetch(fetchCtx, req.ID)
    if err != nil {
        return fmt.Errorf("fetch %s: %w", req.ID, err)
    }
    // ...
}

NEVER ignore context cancellation in select:

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

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

6. Avoid Mutable Globals

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

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

7. sync.Once for Lazy Initialization

type Client struct {
    initOnce sync.Once
    conn     *grpc.ClientConn
}

func (c *Client) getConn() *grpc.ClientConn {
    c.initOnce.Do(func() {
        c.conn = dial()
    })
    return c.conn
}

Race Detection

ALWAYS run tests with race detector during CI:

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

GitHub 저장소

eduardo-sl/go-agent-skills
경로: skills/(safety)/go-concurrency-review
0
FAQ

자주 묻는 질문

go-concurrency-review Skill이란 무엇인가요?

go-concurrency-review은(는) eduardo-sl이(가) 만든 Claude Skill입니다. Skill은 Claude가 필요할 때 불러오는 지침과 리소스를 묶어 추가 프롬프트 없이 go-concurrency-review 관련 작업을 수행할 수 있게 합니다.

go-concurrency-review은(는) 어떻게 설치하나요?

이 페이지의 설치 명령을 사용하세요. go-concurrency-review을(를) Claude Code 플러그인으로 추가하거나 저장소를 skills 디렉터리에 복제한 다음 Claude를 다시 시작해 Skill을 불러옵니다.

go-concurrency-review은(는) 어떤 카테고리에 속하나요?

go-concurrency-review은(는) 테스팅 카테고리에 속합니다.

go-concurrency-review은(는) 무료로 사용할 수 있나요?

네. go-concurrency-review은(는) AIMCP에 등록되어 있으며 무료로 설치할 수 있습니다.

연관 스킬

evaluating-llms-harness
테스팅

이 Claude Skill은 MMLU, GSM8K를 포함한 60개 이상의 표준화된 학술 과제에서 LLM 성능을 벤치마크하기 위해 lm-evaluation-harness를 실행합니다. 개발자들이 모델 품질을 비교하고, 학습 진행 상황을 추적하거나 학술 결과를 보고할 수 있도록 설계되었습니다. 이 도구는 HuggingFace와 vLLM 모델을 포함한 다양한 백엔드를 지원합니다.

스킬 보기
cloudflare-cron-triggers
테스팅

이 스킬은 cron 표현식을 사용하여 Worker를 스케줄링하기 위한 Cloudflare Cron Triggers 구현에 관한 포괄적인 지식을 제공합니다. 주기적 작업, 유지보수 작업, 자동화된 워크플로우 설정 방법을 다루며, 잘못된 cron 표현식이나 시간대 문제 같은 일반적인 이슈들을 해결하는 방법을 포함합니다. 개발자들은 이를 통해 스케줄된 핸들러 구성, cron 트리거 테스트, Workflows 및 Green Compute와의 연동 작업을 수행할 수 있습니다.

스킬 보기
webapp-testing
테스팅

이 Claude Skill은 Python 스크립트를 통해 로컬 웹 애플리케이션을 테스트하기 위한 Playwright 기반 툴킷을 제공합니다. 프론트엔드 검증, UI 디버깅, 스크린샷 캡처, 로그 확인 기능을 지원하며 서버 라이프사이클을 관리합니다. 브라우저 자동화 작업에 사용하되 컨텍스트 오염을 방지하기 위해 소스 코드를 읽지 않고 스크립트를 직접 실행하세요.

스킬 보기
finishing-a-development-branch
테스팅

이 스킬은 테스트 통과를 확인한 후 체계적인 통합 옵션을 제시하여 개발자가 완성된 작업을 마무리하도록 돕습니다. 구현이 완료된 후 머지, PR 생성, 브랜치 정리와 같은 워크플로우를 안내합니다. 코드가 준비되고 테스트가 완료되었을 때 개발 프로세스를 체계적으로 마무리하기 위해 사용하세요.

스킬 보기