mcpField
C
concurrency-patterns

concurrency-patterns

github.com/aj-geddes开发373472 次安装34 周前更新
代码仓库

关于 concurrency-patterns

用于借助同步原语和并行执行模式实现安全并发代码的 Skill。参考内容包括 TypeScript、Node.js、Python 和 Go 风格示例。

主要功能

  1. 01TypeScript Promise 池模式
  2. 02互斥锁与信号量指南
  3. 03Node.js 工作池模式
  4. 04Python 线程与 asyncio 模式
  5. 05Go 风格通道模拟
  6. 06并发安全实践

适用场景

  1. 01限制并行任务执行数量
  2. 02协调并发工作进程
  3. 03防止共享状态发生竞态
  4. 04在 Python 中应用异步模式

安装

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

$npx skills add https://github.com/aj-geddes/useful-ai-prompts --skill concurrency-patterns

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

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
async-patterns-python-asyncio.md
go-style-channels-simulation.md
mutex-and-semaphore-typescript.md
promise-pool-typescript.md
python-threading-patterns.md
worker-pool-nodejs.md
scripts/
validate-api.sh
templates/
api-scaffold.yaml

详细介绍

并发模式

目录

概述

使用恰当的同步原语和模式,实现安全的并发代码以支持并行执行。

适用场景

  • 多线程应用
  • 并行数据处理
  • 防止竞态条件
  • 资源池
  • 任务协调
  • 高性能系统
  • 异步操作
  • 工作线程池

快速入门

最小可运行示例:

class PromisePool {
  private queue: Array<() => Promise<any>> = [];
  private active = 0;

  constructor(private concurrency: number) {}

  async add<T>(fn: () => Promise<T>): Promise<T> {
    while (this.active >= this.concurrency) {
      await this.waitForSlot();
    }

    this.active++;

    try {
      return await fn();
    } finally {
      this.active--;
    }
  }

  private async waitForSlot(): Promise<void> {
    return new Promise((resolve) => {
      const checkSlot = () => {
        if (this.active < this.concurrency) {
          resolve();
// ... (see reference guides for full implementation)

参考指南

references/ 目录中的详细实现:

指南内容
Promise Pool (TypeScript)Promise Pool (TypeScript)
Mutex and Semaphore (TypeScript)Mutex and Semaphore (TypeScript)
Worker Pool (Node.js)Worker Pool (Node.js)
Python Threading PatternsPython Threading Patterns
Async Patterns (Python asyncio)Async Patterns (Python asyncio)
Go-Style Channels (Simulation)Go-Style Channels (Simulation)

最佳实践

✅ 应该
  • 使用恰当的同步原语
  • 限制并发量,避免资源耗尽
  • 处理并发操作中的错误
  • 尽可能使用不可变数据
  • 彻底测试并发代码
  • 分析并发性能
  • 记录线程安全保证
❌ 不应该
  • 在没有同步的情况下共享可变状态
  • 使用休眠/轮询进行协调
  • 创建无限数量的线程/工作线程
  • 忽略竞态条件
  • 在异步代码中阻塞事件循环
  • 忘记清理资源

评论

支持 Markdown