---
title: "动态并行 Step"
description: "为每一项各运行一次同一个 Step 类型，同时进行。分支数量要到运行时才知道时使用，例如订单的每一行一个分支。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/parallel/dynamic-parallel-steps/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/parallel/dynamic.mdx"
locale: "zh-Hans"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# 动态并行 Step

本页代码为 Python。其他语言：[Go](https://docs.superdurable.io/zh-Hans/design-patterns/parallel/dynamic-parallel-steps.go.md) · [Java](https://docs.superdurable.io/zh-Hans/design-patterns/parallel/dynamic-parallel-steps.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/design-patterns/parallel/dynamic-parallel-steps.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/design-patterns/parallel/dynamic-parallel-steps.rust.md)

为每一项各运行一次同一个 Step 类型，同时进行。分支数量要到运行时才知道时使用，例如订单的每一行一个分支。

**Flow 图：DynamicParallelStepsFlow**

**Step 列表**

1. `InitStep`（起始 Step）：Start as many work Steps as the input asks for. 下一步：`DoWork`。
2. `DoWork`：Do one unit of work. 下一步：Flow 完成。

例子: [examples/python/dex_examples/patterns/parallel/dynamic_parallel_steps_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/parallel/dynamic_parallel_steps_flow.py)

<a id="how-it-works"></a>

## 工作方式

**InitStep** 为每个输入项创建一个 `DoWork` movement。Dex 并发运行这些 execution。每个 execution 随机等待一小段时间，所以它们完成的先后不固定。

把每一项的 key 传给它的分支，这样每个结果都能对应回它的输入。一个 Flow run 中活跃的 Step execution 数量[有上限](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#step-and-channel-limits)，正在等待的 Step 也计入。可能变得很大的 fan-out 要分批，或者拆到[子 Flow](https://docs.superdurable.io/zh-Hans/design-patterns.md#subflows) 中。

<a id="core-implementation"></a>

## 核心实现

**Python**

```python
class DoWork(Step[int]):
    async def execute(  # type: ignore[override]
        self, context: AsyncContext, input: int
    ) -> StepDecision:
        await asyncio.sleep(random.uniform(0.05, 0.5))
        return graceful_complete(input)


class InitStep(Step[int]):
    def execute(self, context: Context, input: int) -> StepDecision:
        return go_to_many(
            *(StepMovement.of(DoWork, index) for index in range(input))
        )
```

例子: [examples/python/dex_examples/patterns/parallel/dynamic_parallel_steps_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/parallel/dynamic_parallel_steps_flow.py)

<a id="next"></a>

## 下一步

- [等待并行 Step](https://docs.superdurable.io/zh-Hans/design-patterns/parallel/await-parallel-steps.md)
- [并行 Step](https://docs.superdurable.io/zh-Hans/design-patterns.md#parallel)
