AIコーディング 2026.04.24
Claude Code サブエージェント並列実行ガイド【2026年版】tmux・asyncioで5タスク同時処理
なぜ並列化が必要か
シングルエージェント(1タスク×5回):
ボタン実装 → フォーム実装 → API実装 → テスト → ドキュメント
合計時間: 各5分 × 5 = 25分
サブエージェント並列実行(5タスク同時):
ボタン・フォーム・API・テスト・ドキュメントを同時実行
合計時間: 約5〜7分(最も遅いタスクに依存)
方法1: tmuxで複数の Claude Code CLIを並列起動
#!/bin/bash
# parallel_agents.sh
# tmuxで複数のClaude Codeを並列起動する
# tmuxセッションを作成
tmux new-session -d -s agents
# 5ペインに分割
tmux split-window -h -t agents
tmux split-window -v -t agents:0.0
tmux split-window -v -t agents:0.1
# 各ペインでClaude Codeを起動して異なるタスクを実行
# タスク1: UIコンポーネント
tmux send-keys -t agents:0.0 \
'cd ~/project && claude "src/components/Button.tsxを実装して。TypeScript + Tailwind CSS"' Enter
# タスク2: APIルート
tmux send-keys -t agents:0.1 \
'cd ~/project && claude "src/api/user.ts のCRUD APIを実装して。Zodでバリデーション"' Enter
# タスク3: テスト
tmux send-keys -t agents:0.2 \
'cd ~/project && claude "既存のsrc/utils/以下のコードにpytestユニットテストを書いて"' Enter
# タスク4: ドキュメント
tmux send-keys -t agents:0.3 \
'cd ~/project && claude "src/以下の全publicな関数にJSDocコメントを追加して"' Enter
# セッションを表示
tmux attach-session -t agents
# 実行方法
chmod +x parallel_agents.sh
./parallel_agents.sh
# 全タスク完了後にセッション削除
tmux kill-session -t agents
方法2: Pythonのasyncioで並列APIコール
# parallel_api.py
# asyncio.gather()でClaude APIを並列呼び出し
import asyncio
import anthropic
import time
client = anthropic.Anthropic()
async def claude_task(task_name: str, prompt: str) -> dict:
"""単一タスクを非同期で実行する"""
t = time.time()
# Note: anthropic SDKは同期のみだが、to_threadで非同期化できる
response = await asyncio.to_thread(
client.messages.create,
model="claude-sonnet-4-5",
max_tokens=2048,
messages=[{"role": "user", "content": prompt}]
)
return {
"task": task_name,
"result": response.content[0].text,
"elapsed_s": round(time.time() - t, 1),
"tokens": response.usage.output_tokens,
}
async def parallel_tasks(tasks: list[dict]) -> list[dict]:
"""複数タスクを並列実行する"""
coroutines = [
claude_task(t["name"], t["prompt"])
for t in tasks
]
results = await asyncio.gather(*coroutines)
return list(results)
# タスク定義
TASKS = [
{
"name": "Button",
"prompt": "TypeScript + Tailwind CSSでButtonコンポーネントを実装して。variant: primary/secondary/danger"
},
{
"name": "Form",
"prompt": "React Hook FormでログインFormコンポーネントを実装して。Zodバリデーション付き"
},
{
"name": "API",
"prompt": "FastAPIでユーザーCRUD APIを実装して。Pydanticでバリデーション"
},
{
"name": "Tests",
"prompt": "以下のPython関数のpytestテストを書いて: def add(a, b): return a + b"
},
]
async def main():
print(f"並列実行: {len(TASKS)}タスク")
t_start = time.time()
results = await parallel_tasks(TASKS)
total_time = round(time.time() - t_start, 1)
print(f"\n完了: {total_time}秒(逐次なら約{len(TASKS) * 5}秒相当)")
for r in results:
print(f"\n=== {r['task']} ({r['elapsed_s']}s / {r['tokens']} tokens) ===")
print(r["result"][:300])
asyncio.run(main())
コンテキストを共有する(型定義・共通ルール)
# shared_context_tasks.py
# 共通の型定義を先に生成してから、依存タスクを並列実行する
SHARED_RULES = """
# プロジェクト共通ルール
- TypeScript strict mode
- 関数は純粋関数で書く
- コメントは日本語でJSDoc形式
- ファイル名はkebab-case
# 型定義(事前生成済み)
interface User {
id: string;
email: string;
createdAt: Date;
}
"""
async def phase1_types() -> str:
"""Phase 1: 型定義を先に生成する"""
result = await claude_task(
"types",
"Userエンティティの共通型定義をTypeScriptで生成して"
)
return result["result"]
async def phase2_components(type_defs: str) -> list[dict]:
"""Phase 2: 型定義を受け取って並列でコンポーネントを生成する"""
tasks = [
{
"name": f"comp_{i}",
"prompt": f"""
以下の型定義を使って、コンポーネント{i}を実装してください。
型定義:
{type_defs}
実装: コンポーネント{i}のReactコンポーネント
"""
}
for i in range(3)
]
return await parallel_tasks(tasks)
async def main():
# Phase 1: 型定義生成
print("Phase 1: 型定義を生成中...")
type_defs = await phase1_types()
# Phase 2: 型定義を共有してコンポーネントを並列生成
print("Phase 2: コンポーネントを並列生成中...")
components = await phase2_components(type_defs)
print(f"完了: {len(components)}コンポーネント生成")
asyncio.run(main())
あわせて読みたい
- OpusがSonnetを指揮する2モデル協調パターン|コスト30%削減のPython実装
- Claude Codeで午前中に機能完成する方法|16のロール活用で爆速開発
- AIコード生成の品質管理|失敗5パターンと品質ゲートスクリプト