mcpField
G
go-concurrency-patterns

go-concurrency-patterns

github.com/wshobson开发41.9k11.4k 次安装2 周前更新
代码仓库

关于 go-concurrency-patterns

面向 Go 开发者的生产级并发模式指南,介绍 goroutine、channel、同步、context 处理和生命周期管理。

主要功能

  1. 01并发原语概览
  2. 02工作池与流水线
  3. 03goroutine 生命周期管理
  4. 04同步与取消处理
  5. 05竞态条件排查

适用场景

  1. 01构建 Go 并发应用
  2. 02实现工作池
  3. 03优雅关闭 goroutine
  4. 04排查竞态条件

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/wshobson/agents --skill go-concurrency-patterns

安装后在 Claude Code 中输入/go-concurrency-patterns确认已加载。

附带文件references/details.md

详细介绍

Go 并发模式

用于生产的 Go 并发模式,包括 goroutine、channel、同步原语和上下文管理。

何时使用本技能

  • 构建 Go 并发应用
  • 实现 worker 和流水线
  • 管理 goroutine 生命周期
  • 使用 channel 进行通信
  • 调试竞态条件
  • 实现优雅关闭

核心概念

1. Go 并发原语
原语说明
goroutine轻量级并发执行
channelgoroutine 之间的通信
select多路复用 channel 操作
sync.Mutex互斥
sync.WaitGroup等待 goroutine 完成
context.Context取消和截止时间
2. Go 并发箴言
Don't communicate by sharing memory;
share memory by communicating.

快速开始

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    results := make(chan string, 10)
    var wg sync.WaitGroup

    // Spawn workers
    for i := 0; i < 3; i++ {
        wg.Add(1)
        go worker(ctx, i, results, &wg)
    }

    // Close results when done
    go func() {
        wg.Wait()
        close(results)
    }()

    // Collect results
    for result := range results {
        fmt.Println(result)
    }
}

func worker(ctx context.Context, id int, results chan<- string, wg *sync.WaitGroup) {
    defer wg.Done()

    select {
    case <-ctx.Done():
        return
    case results <- fmt.Sprintf("Worker %d done", id):
    }
}

详细模式与完整示例

详细模式文档位于 references/details.md。当上述导航层级不够用时,请阅读该文件。

最佳实践

应该做的
  • 使用 context —— 用于取消和截止时间
  • 关闭 channel —— 只从发送方关闭
  • 使用 errgroup —— 用于带错误的并发操作
  • 为 channel 设置缓冲 —— 当你知道数量时
  • 优先使用 channel —— 尽可能代替互斥锁
不应该做的
  • 不要泄漏 goroutine —— 始终要有退出路径
  • 不要从接收方关闭 —— 会导致 panic
  • 不要使用共享内存 —— 除非必要
  • 不要忽略 context 取消 —— 检查 ctx.Done()
  • 不要用 time.Sleep 做同步 —— 使用合适的原语

评论

支持 Markdown