executeParallel 并行执行无依赖的步骤
(ctx context.Context, plan *ExecutionPlan, toolCtx *tools.ToolContext)
| 175 | |
| 176 | // executeParallel 并行执行无依赖的步骤 |
| 177 | func (e *Executor) executeParallel(ctx context.Context, plan *ExecutionPlan, toolCtx *tools.ToolContext) error { |
| 178 | // 构建步骤依赖图 |
| 179 | completed := make(map[string]bool) |
| 180 | var mu sync.Mutex |
| 181 | var wg sync.WaitGroup |
| 182 | var firstError error |
| 183 | var errMu sync.Mutex |
| 184 | |
| 185 | maxParallel := plan.Options.MaxParallelSteps |
| 186 | if maxParallel <= 0 { |
| 187 | maxParallel = 3 // 默认最多3个并行 |
| 188 | } |
| 189 | sem := make(chan struct{}, maxParallel) |
| 190 | |
| 191 | for { |
| 192 | // 找出所有可以执行的步骤 |
| 193 | var readySteps []*Step |
| 194 | mu.Lock() |
| 195 | for i := range plan.Steps { |
| 196 | step := &plan.Steps[i] |
| 197 | if step.Status != StepStatusPending { |
| 198 | continue |
| 199 | } |
| 200 | if e.checkDependenciesWithMap(step, completed) { |
| 201 | readySteps = append(readySteps, step) |
| 202 | } |
| 203 | } |
| 204 | mu.Unlock() |
| 205 | |
| 206 | // 如果没有可执行的步骤,检查是否全部完成 |
| 207 | if len(readySteps) == 0 { |
| 208 | // 检查是否还有未完成的步骤 |
| 209 | allDone := true |
| 210 | for i := range plan.Steps { |
| 211 | if plan.Steps[i].Status == StepStatusPending || plan.Steps[i].Status == StepStatusRunning { |
| 212 | allDone = false |
| 213 | break |
| 214 | } |
| 215 | } |
| 216 | if allDone { |
| 217 | break |
| 218 | } |
| 219 | // 等待正在执行的步骤完成 |
| 220 | time.Sleep(100 * time.Millisecond) |
| 221 | continue |
| 222 | } |
| 223 | |
| 224 | // 并行执行准备好的步骤 |
| 225 | for _, step := range readySteps { |
| 226 | select { |
| 227 | case <-ctx.Done(): |
| 228 | return ctx.Err() |
| 229 | case sem <- struct{}{}: |
| 230 | } |
| 231 | |
| 232 | wg.Add(1) |
| 233 | go func(s *Step) { |
| 234 | defer wg.Done() |
no test coverage detected