跳至正文
OpenAgentSkill
浏览已开放 · 目录记录日期 2026-11-21 · 自动更新和账户服务暂时关闭。
开发与测试

go-concurrency-practice

Enforces practical Go concurrency rules from "100 Go Mistakes" (Ch.9, #61-#74) when writing or reviewing concurrent Go code. Use when code involves goroutines, channels, select statements, sync primitives (Mutex, WaitGroup, Cond, errgroup), or when passing contexts across goroutine boundaries. Catches context propagation bugs, goroutine leaks, loop variable captures, channel misuse, data races with append/slices/maps, sync type copying, and deadlocks from string formatting.

v0lka · 已有静态检查记录

安装与使用

运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。

npx skills add v0lka/skills --skill go-concurrency-practice

技能说明


name: go-concurrency-practice description: > Enforces practical Go concurrency rules from "100 Go Mistakes" (Ch.9, #61-#74) when writing or reviewing concurrent Go code. Use when code involves goroutines, channels, select statements, sync primitives (Mutex, WaitGroup, Cond, errgroup), or when passing contexts across goroutine boundaries. Catches context propagation bugs, goroutine leaks, loop variable captures, channel misuse, data races with append/slices/maps, sync type copying, and deadlocks from string formatting.

Go Concurrency Practice Rules

Context & Goroutine Lifecycle

#61: Do not propagate a cancel-bound context into a goroutine that must outlive it

When spawning a goroutine from an HTTP handler (or any scoped context) to do async work (e.g., publish to Kafka, send metrics), do not pass the request context directly. The context cancels when the response is written, racing with the async work.

Rules:

  • If the goroutine must outlive the parent scope, use context.Background() or a detached context that preserves values but strips cancellation.
  • If values (trace IDs, correlation IDs) must be carried, create a detach wrapper:
// detach strips cancellation/deadline but keeps values.
type detach struct{ ctx context.Context }

func (d detach) Deadline() (time.Time, bool) { return time.Time{}, false }
func (d detach) Done() <-chan struct{}        { return nil }
func (d detach) Err() error                  { return nil }
func (d detach) Value(key any) any           { return d.ctx.Value(key) }
// BAD - context cancels when response is written
go func() { publish(r.Context(), response) }()

// GOOD - detach cancellation, keep values
go func() { publish(detach{ctx: r.Context()}, response) }()

#62: Every goroutine must have a known stopping condition

Before writing go func(), answer: when does this goroutine stop?

Rules:

  • If a goroutine holds resources (connections, files), the parent must wait for cleanup, not just signal. Use defer w.close() or a sync.WaitGroup.
  • Signaling (context cancellation) is not enough on its own -- it does not guarantee the goroutine had time to release resources.
  • Return the goroutine's owner (struct with a Close method) so the caller can manage its lifetime.
// BAD - no way to wait for cleanup
func newWatcher(ctx context.Context) {
    w := watcher{}
    go w.watch(ctx)
}

// GOOD - caller controls shutdown
func newWatcher() watcher {
    w := watcher{}
    go w.watch()
    return w
}
// in main:
w := newWatcher()
defer w.close()

Goroutines & Loop Variables

#63: Capture loop variables before launching goroutines

Closure goroutines capture the variable, not the value. All goroutines share the same loop variable and will read whatever value it holds at execution time.

Rules:

  • Create a local copy: val := i before the go func().
  • Or pass the variable as a function argument: go func(v int) { ... }(i).

Note: Go 1.22+ changed for loop variable semantics so each iteration gets a new variable. If the module's go directive is >= 1.22, this is no longer a bug, but applying the fix is still safe and communicates intent.

// BAD (before Go 1.22)
for _, i := range s {
    go func() { fmt.Print(i) }() // may print same value repeatedly
}

// GOOD - local copy
for _, i := range s {
    val := i
    go func() { fmt.Print(val) }()
}

// GOOD - function argument
for _, i := range s {
    go func(val int) { fmt.Print(val) }(i)
}

Channel Patterns

#64: select on multiple channels picks randomly, not by source order

When multiple cases in a select can proceed, Go picks one uniformly at random. Writing case <-messageCh above case <-disconnectCh does not create priority.

Rules:

  • For a single producer: use an unbuffered channel or a single channel carrying both message types to enforce ordering.
  • For multiple producers needing priority drain: after receiving the low-priority signal, use an inner for/select with default to drain the high-priority channel.
// Priority drain pattern
for {
    select {
    case v := <-messageCh:
        fmt.Println(v)
    case <-disconnectCh:
        // Drain remaining messages before returning
        for {
            select {
            case v := <-messageCh:
                fmt.Println(v)
            default:
                return
            }
        }
    }
}

#65: Use chan struct{} for notification channels

If a channel carries no meaningful data (only the event of receiving matters), use chan struct{}, not chan bool. An empty struct is zero bytes; bool wastes space and creates ambiguity about what false means.

#66: Use nil channels to disable select cases

Receiving from or sending to a nil channel blocks forever. This is useful: after a channel is closed, set it to nil to remove that case from a select.

Key pattern -- merging channels:

func merge(ch1, ch2 <-chan int) <-chan int {
    ch := make(chan int, 1)
    go func() {
        for ch1 != nil || ch2 != nil {
            select {
            case v, open := <-ch1:
                if !open {
                    ch1 = nil // disable this case
                    break
                }
                ch <- v
            case v, open := <-ch2:
                if !open {
                    ch2 = nil
                    break
                }
                ch <- v
            }
        }
        close(ch)
    }()
    return ch
}

Without nil channels the closed-channel case fires continuously in a busy loop (receiving the zero value), wasting CPU.

#67: Default buffered channel size should be 1

  • Use unbuffered channels when you need synchronization (sender blocks until receiver is ready) or for close-based notifications.
  • Use buffered with size 1 as the default when a buffer is needed.
  • Only use larger sizes for:
阅读完整来源 ↗