Claude Code Parallel Tasks
Claude Code provides multiple mechanisms for parallel task execution, allowing you to handle multiple work items simultaneously and significantly improve development efficiency. This chapter introduces three main parallelization approaches: Subagents, Agent Teams, and Git Worktree, helping you choose the most suitable method for different usage scenarios.
Parallel Tasks Overview
When faced with complex tasks, a single Claude instance may be insufficient—context becoming too long, responses slowing down, and tasks interleaving. Claude Code provides a three-tier parallelization mechanism to meet different complexity and collaboration needs:
| Mechanism | Applicable Scenarios | Collaboration Method | Complexity |
|---|---|---|---|
| Subagents | Focused tasks, only need to care about results | One-way reporting (results returned to the main agent) | Low |
| Agent Teams | Complex work requiring discussion and collaboration | Multi-directional communication (teammates message each other directly) | Medium |
| Git Worktree | Multiple tasks requiring isolated code environments | Fully independent (each with its own working directory) | Medium |
Selection suggestions:
- For independent subtasks that simply need parallel processing → useSubagents
- For multiple agents needing to discuss and coordinate work → useAgent Teams
- For multiple tasks needing to operate on different branches of the same repository → useGit Worktree
Subagents
What are Subagents
A Subagent is an independently running Claude instance with its own context and task focus. The main Claude can create multiple Subagents, each responsible for a specific subtask:
┌─────────────────────────────────────────────────────────┐
│ 主 Claude │
│ (协调者) │
└─────────────────────────────────────────────────────────┘
│
▼
┌───────────────┼───────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Agent A │ │ Agent B │ │ Agent C │
│ 代码审查 │ │ 测试生成 │ │ 文档编写 │
└──────────┘ └──────────┘ └──────────┘
│ │ │
└───────────────┴───────────────┘
│
▼
返回结果给主代理
Up to 49 Subagents can run in parallel, fully meeting most parallel processing needs.
Built-in Subagents
Claude Code comes with the following built-in Subagents:
| Agent | Model | Tools | Purpose |
|---|---|---|---|
Explore |
Haiku (fast, low latency) | Read-only tools | File discovery, code search, codebase exploration |
Plan |
Inherits main conversation | Read-only tools | Codebase research in planning mode |
General-purpose |
Inherits main conversation | All tools | Complex research, multi-step operations, code modification |
statusline-setup |
Sonnet | — | Run/statuslineConfigure the status line |
Claude Code Guide |
Haiku | — | Answer questions about Claude Code features |
Creating a Subagent
Method 1: Use the /agents command
Run/agentscommand, and follow the prompts to create a new Subagent:
/agents
ChooseCreate new agent, then choose a save location, describe the functionality, and let Claude generate the configuration.
Method 2: Manually create a Subagent file
Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:
Example
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---
You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.
Subagent Configuration Fields
| Field | Required | Description |
|---|---|---|
name |
Yes | Unique identifier using lowercase letters and hyphens |
description |
Yes | Describes when Claude should delegate to this Subagent |
tools |
no | List of tools the Subagent can use |
disallowedTools |
no | Tools to deny |
model |
no | Model to use: sonnet, opus, haiku, or inherit |
permissionMode |
no | Permission mode: default, acceptEdits, auto, dontAsk, bypassPermissions, plan |
maxTurns |
no | Maximum agent turns before the Subagent stops |
skills |
no | Skills loaded at startup |
mcpServers |
no | MCP servers available to this Subagent |
memory |
no | Persistent memory scope: user, project, or local |
background |
no | Whether to always run as a background task |
isolation |
no | Set to worktree to run in a temporary git worktree |
Controlling Subagent Capabilities
Tool restrictions
Example
---
name: safe-researcher
description: Research agent with restricted capabilities
tools: Read, Grep, Glob, Bash
---
# Exclude specific tools
---
name: no-writes
description: Inherits every tool except file writes
disallowedTools: Write, Edit
---
Model selection
Example
---
name: quick-searcher
description: Quick file search
model: haiku
---
# Use Opus (powerful, expensive)
---
name: deep-analyst
description: Deep code analysis
model: opus
---
# Inherit the main conversation model
---
name: general-purpose
model: inherit
---
Invoking Subagents
Method 1: Natural language
Use the test-runner subagent to fix failing tests
Method 2: @-mention
@"code-reviewer (agent)" look at the auth changes
Method 3: Command-line launch
claude --agent code-reviewer
Foreground and Background Execution
- Foreground Subagent: Blocks the main conversation until completion
- Background Subagent: Runs concurrently, press to
Ctrl+Bswitch
Agent Teams
What are Agent Teams
Agent Teams allows you to coordinate multiple Claude Code instances working together. Imagine simultaneously running 4 Claude sessions (A, B, C, D), where one acts as the team leader, responsible for coordinating work, assigning tasks, and integrating results. The other three members each work independently with their own context windows, while also being able to communicate directly with one another.
Subagents vs Agent Teams
| Characteristics | Subagents | Agent Teams |
|---|---|---|
| Context | Own context window; results returned to the caller | Own context window; completely independent |
| Communication | Only reports results to the main agent | Send messages directly to each other between teammates |
| Coordination | The main agent manages all work | Shared task list, supports self-coordination |
| Best for | Focused tasks that only require attention to results | Complex work requiring discussion and collaboration |
| Token cost | Lower: results are summarized back into the main context | Higher: each teammate is an independent Claude instance |
In simple terms:Subagent is like an employee reporting to the boss; Agent Teams is a project group of peers collaborating equally.。
Enabling Agent Teams
Agent Teams is disabled by default. You need to add it insettings.json:
Example
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
}
}
Or set the environment variable:
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
Requirements: Claude Code v2.1.32 or higher
Starting an Agent Team
Once enabled, describe the task and team structure in natural language:
Example
their codebase. Create an agent team to explore this from different angles: one
teammate on UX, one on technical architecture, one playing devil's advocate.
Controlling an Agent Team
Display mode
- In-process: All teammates run in the main terminal, use
Shift+Downto cycle through teammates - Split panes: Each teammate gets their own tmux/iTerm2 pane
Example
"teammateMode": "in-process"
}
Specifying the number of teammates and models
Create a team with 4 teammates to refactor these modules in parallel. Use Sonnet for each teammate.
Task assignment
- The lead can explicitly assign tasks
- Teammates can self-assign unassigned, unblocked tasks
- Tasks have three states: pending, in progress, and completed
Interacting with teammates
- In-process:
Shift+DownCycle through → enter a message →EnterView →EscapeInterrupt - Split-pane: Click a teammate's pane to interact directly
Closing teammates
Ask the researcher teammate to shut down
Agent Teams Architecture
| Components | Roles |
|---|---|
| Team Lead | The main Claude Code session that creates the team, spawns teammates, and coordinates work |
| Teammates | Independent Claude Code instances, each handling assigned tasks |
| Task List | A shared list of work items that teammates claim and complete |
| Mailbox | A message system for communication between agents |
Storage location:
- Team config:
~/.claude/teams/{team-name}/config.json - Task list:
~/.claude/tasks/{team-name}/
Git Worktree Support
Problem Background
When multiple agents work at the same time, they may "fight" each other. Imagine this scenario: you ask Agent A to refactor the database module and Agent B to fix a bug on the login page. The two tasks seem unrelated, but they both work in the same code repository and on the same branch. Agent A is modifyingutils.py, and Agent B is also modifyingutils.py. One saves one version, the other overwrites it with a different version, ultimately leading to conflicts, errors, and even data loss.
This is not an AI problem; it is a limitation of the underlying Git repository structure.
What is Git Worktree
Git Worktree is a Git feature that lets you mount multiple independent working directories on the same repository. Each working directory has its own branch, its own HEAD, and its own staging area, but they all share the same.gitdatabase (history, object storage).
Analogy
each office has a different team (Agent), each working on a different project (branch),
but they all share the company's database (.git) and history."
Using Git Worktree
Starting from the command line
# 创建 feature-auth 分支的工作树 claude -w feature-auth # 同时创建 tmux 会话 claude -w feature-auth --tmux # 使用传统 tmux claude -w feature-auth --tmux=classic
CLI parameters
| Parameter | Description | Example |
|---|---|---|
--worktree, -w |
Start Claude in an isolated git worktree | claude -w feature-auth |
--tmux |
Create a tmux session for the worktree | claude -w feature-auth --tmux |
Worktree creation location:<repo>/.claude/worktrees/<name>
Desktop support
In the Claude desktop app, go to the Code tab and simply check worktree mode to enable workspace mode.
Subagent + Worktree Isolation
You can have custom Subagents always run in their own worktree:
Example
name: background-refactorer
description: Background refactoring agent
isolation: worktree
---
Usage Examples
Example 1: Parallel Code Review
Using Subagents
Use the security-reviewer subagent to check for security issues
Use the performance-reviewer subagent to analyze performance impact
Use the test-coverage subagent to validate test coverage
Using Agent Teams
- One focused on security implications
- One checking performance impact
- One validating test coverage
Have them each review and report findings.
Example 2: Parallel Research
Research the authentication, database, and API modules in parallel using separate subagents
Example 3: Investigation with Competing Hypotheses
Example
Spawn 5 agent teammates to investigate different hypotheses. Have them talk to
each other to try to disprove each other's theories, like a scientific
debate. Update the findings doc with whatever consensus emerges.
Example 4: Multi-branch Development
# 终端 1:重构用户模块 claude -w feature/user-refactor # 终端 2:修复登录 bug claude -w bugfix/login-issue # 终端 3:开发新功能 claude -w feature/new-dashboard
Example 5: Chaining Subagents
Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them
Best Practices
Subagent Best Practices
- Stay Focused: Each Subagent should have a clear, single responsibility
- Limit Tools: Restrict Subagent tool access based on task requirements
- Choose Appropriate Model: Use Haiku for simple tasks, Sonnet or Opus for complex tasks
- Use Background Execution: Use background Subagents for long-running tasks to avoid blocking the main conversation
- Resume Subagent: When you need to continue work, ask Claude to resume the Subagent
Agent Teams Best Practices
- Give Teammates Enough Context: Include task-specific details in the generated prompts
- Choose Appropriate Team Size: Most workflows start with 3-5 teammates
- Right-Size Tasks: 5-6 tasks per teammate keeps productivity high
- Wait for Teammates to Complete: Tell the lead to wait for teammates to finish before proceeding
- Start with Research and Review: Start with tasks that don't require writing code
- Avoid File Conflicts: Break up work so each teammate owns a different set of files
- Monitor and Guide: Check progress, redirect approaches that aren't working
Git Worktree Best Practices
- One Worktree per Task: Avoid working on multiple unrelated tasks in the same worktree
- Use tmux Management: When running multiple Claude sessions simultaneously, use tmux for easy switching
- Clean Up Unneeded Worktrees: Delete worktrees promptly after task completion
Troubleshooting
Agent Teams FAQ
| Problem | Solution |
|---|---|
| Teammate does not appear | Check whether the task is complex enough and whether tmux is installed |
| Too many permission prompts | Pre-approve common operations in permission settings |
| Teammate stops after an error | Check the output and give additional instructions or spawn a replacement teammate |
| Lead shuts down early | Tell the lead to continue or wait for teammates to complete |
| Orphaned tmux sessions | Usetmux lsandtmux kill-session -t <session-name>Clean up |
Practical Subagent Examples
Code Reviewer
Example
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability.
tools: Read, Grep, Glob, Bash
model: inherit
---
You are a senior code reviewer ensuring high standards of code quality and security.
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Review checklist:
- Code is clear and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Debugger
Example
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior.
tools: Read, Edit, Bash, Grep, Glob
---
You are an expert debugger specializing in root cause analysis.
When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works
Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states
Read-only Database Query Tool
Example
name: db-reader
description: Execute read-only database queries. Use when analyzing data or generating reports.
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data.