parallel-execution

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Parallel Execution Patterns

并行执行模式

When to Load

何时加载

  • Trigger: Multi-agent tasks, concurrent operations, spawning subagents, parallelizing independent work
  • Skip: Single-step tasks or sequential workflows with no parallelization opportunity
  • 触发场景:多Agent任务、并发操作、生成子Agent、并行处理独立工作
  • 不适用场景:单步任务,或是没有并行空间的顺序工作流

Core Concept

核心概念

Parallel execution spawns multiple subagents simultaneously using the Task tool with
run_in_background: true
. This enables N tasks to run concurrently, dramatically reducing total execution time.
Critical Rule: ALL Task calls MUST be in a SINGLE assistant message for true parallelism. If Task calls are in separate messages, they run sequentially.
并行执行通过使用带有
run_in_background: true
参数的Task工具同时生成多个子Agent,支持N个任务并发运行,可大幅缩短总执行时间。
关键规则:要实现真正的并行,所有Task调用必须放在同一条助手消息中。如果Task调用分散在不同消息中,它们会按顺序执行。

Execution Protocol

执行流程

Step 1: Identify Parallelizable Tasks

步骤1:识别可并行任务

Before spawning, verify tasks are independent:
  • No task depends on another's output
  • Tasks target different files or concerns
  • Can run simultaneously without conflicts
生成子Agent前,先确认任务之间相互独立:
  • 没有任务依赖其他任务的输出
  • 任务针对不同的文件或业务模块
  • 可同时运行且不会产生冲突

Step 2: Prepare Dynamic Subagent Prompts

步骤2:准备动态子Agent提示词

Each subagent receives a custom prompt defining its role:
You are a [ROLE] specialist for this specific task.

Task: [CLEAR DESCRIPTION]

Context:
[RELEVANT CONTEXT ABOUT THE CODEBASE/PROJECT]

Files to work with:
[SPECIFIC FILES OR PATTERNS]

Output format:
[EXPECTED OUTPUT STRUCTURE]

Focus areas:
- [PRIORITY 1]
- [PRIORITY 2]
每个子Agent都会收到自定义的提示词来定义其角色:
You are a [ROLE] specialist for this specific task.

Task: [CLEAR DESCRIPTION]

Context:
[RELEVANT CONTEXT ABOUT THE CODEBASE/PROJECT]

Files to work with:
[SPECIFIC FILES OR PATTERNS]

Output format:
[EXPECTED OUTPUT STRUCTURE]

Focus areas:
- [PRIORITY 1]
- [PRIORITY 2]

Step 3: Launch All Tasks in ONE Message

步骤3:在同一条消息中启动所有任务

CRITICAL: Make ALL Task calls in the SAME assistant message:
I'm launching N parallel subagents:

[Task 1]
description: "Subagent A - [brief purpose]"
prompt: "[detailed instructions for subagent A]"
run_in_background: true

[Task 2]
description: "Subagent B - [brief purpose]"
prompt: "[detailed instructions for subagent B]"
run_in_background: true

[Task 3]
description: "Subagent C - [brief purpose]"
prompt: "[detailed instructions for subagent C]"
run_in_background: true
关键要求:所有Task调用必须放在同一条助手消息中:
I'm launching N parallel subagents:

[Task 1]
description: "Subagent A - [brief purpose]"
prompt: "[detailed instructions for subagent A]"
run_in_background: true

[Task 2]
description: "Subagent B - [brief purpose]"
prompt: "[detailed instructions for subagent B]"
run_in_background: true

[Task 3]
description: "Subagent C - [brief purpose]"
prompt: "[detailed instructions for subagent C]"
run_in_background: true

Step 4: Retrieve Results with TaskOutput

步骤4:通过TaskOutput获取结果

After launching, retrieve each result:
[Wait for completion, then retrieve]

TaskOutput: task_1_id
TaskOutput: task_2_id
TaskOutput: task_3_id
启动任务后,获取每个任务的执行结果:
[Wait for completion, then retrieve]

TaskOutput: task_1_id
TaskOutput: task_2_id
TaskOutput: task_3_id

Step 5: Synthesize Results

步骤5:整合结果

Combine all subagent outputs into unified result:
  • Merge related findings
  • Resolve conflicts between recommendations
  • Prioritize by severity/importance
  • Create actionable summary
将所有子Agent的输出合并为统一的结果:
  • 合并相关的结论
  • 解决不同建议之间的冲突
  • 按严重程度/优先级排序
  • 生成可落地的总结

Dynamic Subagent Patterns

动态子Agent模式

Pattern 1: Task-Based Parallelization

模式1:基于任务的并行化

When you have N tasks to implement, spawn N subagents:
Plan:
1. Implement auth module
2. Create API endpoints
3. Add database schema
4. Write unit tests
5. Update documentation

Spawn 5 subagents (one per task):
- Subagent 1: Implements auth module
- Subagent 2: Creates API endpoints
- Subagent 3: Adds database schema
- Subagent 4: Writes unit tests
- Subagent 5: Updates documentation
当你有N个待实现的任务时,生成N个子Agent:
Plan:
1. Implement auth module
2. Create API endpoints
3. Add database schema
4. Write unit tests
5. Update documentation

Spawn 5 subagents (one per task):
- Subagent 1: Implements auth module
- Subagent 2: Creates API endpoints
- Subagent 3: Adds database schema
- Subagent 4: Writes unit tests
- Subagent 5: Updates documentation

Pattern 2: Directory-Based Parallelization

模式2:基于目录的并行化

Analyze multiple directories simultaneously:
Directories: src/auth, src/api, src/db

Spawn 3 subagents:
- Subagent 1: Analyzes src/auth
- Subagent 2: Analyzes src/api
- Subagent 3: Analyzes src/db
同时分析多个目录:
Directories: src/auth, src/api, src/db

Spawn 3 subagents:
- Subagent 1: Analyzes src/auth
- Subagent 2: Analyzes src/api
- Subagent 3: Analyzes src/db

Pattern 3: Perspective-Based Parallelization

模式3:基于视角的并行化

Review from multiple angles simultaneously:
Perspectives: Security, Performance, Testing, Architecture

Spawn 4 subagents:
- Subagent 1: Security review
- Subagent 2: Performance analysis
- Subagent 3: Test coverage review
- Subagent 4: Architecture assessment
同时从多个角度进行评审:
Perspectives: Security, Performance, Testing, Architecture

Spawn 4 subagents:
- Subagent 1: Security review
- Subagent 2: Performance analysis
- Subagent 3: Test coverage review
- Subagent 4: Architecture assessment

TodoWrite Integration

TodoWrite集成

When using parallel execution, TodoWrite behavior differs:
Sequential execution: Only ONE task
in_progress
at a time Parallel execution: MULTIPLE tasks can be
in_progress
simultaneously
undefined
使用并行执行时,TodoWrite的行为会有所不同:
顺序执行:同一时间只有1个任务处于
in_progress
状态 并行执行:同一时间可以有多个任务处于
in_progress
状态
undefined

Before launching parallel tasks

Before launching parallel tasks

todos = [ { content: "Task A", status: "in_progress" }, { content: "Task B", status: "in_progress" }, { content: "Task C", status: "in_progress" }, { content: "Synthesize results", status: "pending" } ]
todos = [ { content: "Task A", status: "in_progress" }, { content: "Task B", status: "in_progress" }, { content: "Task C", status: "in_progress" }, { content: "Synthesize results", status: "pending" } ]

After each TaskOutput retrieval, mark as completed

After each TaskOutput retrieval, mark as completed

todos = [ { content: "Task A", status: "completed" }, { content: "Task B", status: "completed" }, { content: "Task C", status: "completed" }, { content: "Synthesize results", status: "in_progress" } ]
undefined
todos = [ { content: "Task A", status: "completed" }, { content: "Task B", status: "completed" }, { content: "Task C", status: "completed" }, { content: "Synthesize results", status: "in_progress" } ]
undefined

When to Use Parallel Execution

何时使用并行执行

Good candidates:
  • Multiple independent analyses (code review, security, tests)
  • Multi-file processing where files are independent
  • Exploratory tasks with different perspectives
  • Verification tasks with different checks
  • Feature implementation with independent components
Avoid parallelization when:
  • Tasks have dependencies (Task B needs Task A's output)
  • Sequential workflows are required (commit -> push -> PR)
  • Tasks modify the same files (risk of conflicts)
  • Order matters for correctness
适用场景:
  • 多个独立分析任务(代码评审、安全检查、测试)
  • 多文件处理且文件之间相互独立
  • 从不同视角开展的探索性任务
  • 包含不同检查项的验证任务
  • 由独立组件构成的功能实现
不建议并行的场景:
  • 任务之间存在依赖(任务B需要任务A的输出)
  • 要求按顺序执行的工作流(提交 -> 推送 -> PR)
  • 任务会修改相同文件(存在冲突风险)
  • 执行顺序会影响结果正确性

Performance Benefits

性能收益

Approach5 Tasks @ 30s eachTotal Time
Sequential30s + 30s + 30s + 30s + 30s~150s
ParallelAll 5 run simultaneously~30s
Parallel execution is approximately Nx faster where N is the number of independent tasks.
执行方式5个任务 @ 每个耗时30秒总耗时
顺序执行30s + 30s + 30s + 30s + 30s~150s
并行执行5个任务同时运行~30s
并行执行的速度提升约为N倍,N为独立任务的数量。

Example: Feature Implementation

示例:功能实现

User request: "Implement user authentication with login, registration, and password reset"
Orchestrator creates plan:
  1. Implement login endpoint
  2. Implement registration endpoint
  3. Implement password reset endpoint
  4. Add authentication middleware
  5. Write integration tests
Parallel execution:
Launching 5 subagents in parallel:

[Task 1] Login endpoint implementation
[Task 2] Registration endpoint implementation
[Task 3] Password reset endpoint implementation
[Task 4] Auth middleware implementation
[Task 5] Integration test writing

All tasks run simultaneously...

[Collect results via TaskOutput]

[Synthesize into cohesive implementation]
用户需求:"实现用户认证功能,包含登录、注册和密码重置"
编排器生成计划
  1. 实现登录接口
  2. 实现注册接口
  3. 实现密码重置接口
  4. 添加认证中间件
  5. 编写集成测试
并行执行
Launching 5 subagents in parallel:

[Task 1] Login endpoint implementation
[Task 2] Registration endpoint implementation
[Task 3] Password reset endpoint implementation
[Task 4] Auth middleware implementation
[Task 5] Integration test writing

All tasks run simultaneously...

[Collect results via TaskOutput]

[Synthesize into cohesive implementation]

Troubleshooting

问题排查

Tasks running sequentially?
  • Verify ALL Task calls are in SINGLE message
  • Check
    run_in_background: true
    is set for each
Results not available?
  • Use TaskOutput with correct task IDs
  • Wait for tasks to complete before retrieving
Conflicts in output?
  • Ensure tasks don't modify same files
  • Add conflict resolution in synthesis step
任务按顺序执行?
  • 确认所有Task调用都放在同一条消息中
  • 检查每个任务是否都设置了
    run_in_background: true
无法获取结果?
  • 使用TaskOutput时传入正确的任务ID
  • 等待任务执行完成后再获取结果
输出存在冲突?
  • 确保任务不会修改相同文件
  • 在结果整合步骤添加冲突解决逻辑