← 中文资源

简体中文版本

WaitGroup 跟踪并行任务收尾

派发前 add 计数、每个任务结束时 done 递减,wait() 等到计数归零才放行主流程;计数在派发前加好,避免任务先于注册完成造成的提前放行竞态。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

cache finished
assets finished
index finished
all parallel jobs drained

实现说明

WaitGroup 跟踪并行任务收尾可以归结为类 WaitGroup和函数 runJob、main。 重复被限制在 for (const [name, ms] of jobs) 里——其余代码按顺序各跑一遍。每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。代码不会带着坏状态静默继续,守卫一命中就抛 Error。

使用要点

  • 守卫 this.released && delta > 0 命中后立刻用提前的 throw 结束这一轮。
  • 演示输出是带标签的(all parallel jobs drained),每个操作都会留下自己的一行标注。
  • main 的演示流程是 runJob——跑一遍文件,这条流程从头到尾可见。

常见问题

前置条件不成立会发生什么?

守卫处(this.released && delta > 0)会抛出 Error,非法状态到不了主逻辑。

运行「WaitGroup 跟踪并行任务收尾」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 all parallel jobs drained 标签标明各步骤。

入口签名:async function runJob(wg: WaitGroup, name: string, ms: number)

核心语句

await new Promise((resolve) => setTimeout(resolve, ms));
if (this.count === 0) return Promise.resolve();
if (this.released && delta > 0) throw new Error('add after wait completed');

代码示例

// WaitGroup: track task completion with a counter; wait() resolves
// once the counter drains to zero
class WaitGroup {
  private count = 0;
  private gate = Promise.withResolvers<void>();
  private released = false;

  add(delta: number): void {
    if (this.released && delta > 0) throw new Error('add after wait completed');
    this.count += delta;
  }

  done(): void {
    if (this.count === 0) throw new Error('done without matching add');
    this.count -= 1;
    if (this.count === 0) {
      this.released = true;
      this.gate.resolve();
    }
  }

  wait(): Promise<void> {
    if (this.count === 0) return Promise.resolve();
    return this.gate.promise;
  }
}

async function runJob(wg: WaitGroup, name: string, ms: number) {
  await new Promise((resolve) => setTimeout(resolve, ms));
  console.log(name, 'finished');
  wg.done();
}

async function main() {
  const wg = new WaitGroup();
  const jobs = [
    ['cache', 15],
    ['index', 40],
    ['assets', 25],
  ] as const;
  wg.add(jobs.length); // count before spawning, not after
  for (const [name, ms] of jobs) {
    void runJob(wg, name, ms);
  }
  await wg.wait();
  console.log('all parallel jobs drained');
}

main();