AI 写的异步条件变量靠谱吗?用九组测试审查等待协议

10-19 5阅读

让 AI 写一个异步条件变量,最容易得到的答案是一个 Promise 集合,加上 wait、notifyOne 和 notifyAll 三个方法。但真正决定它是否可靠的,并不是方法名称是否齐全,而是检查共享状态、登记等待、释放互斥锁、接受通知与重新持锁之间有没有缝隙。本文用九个能独立运行的反例与断言,把这些容易被流畅解释掩盖的细节展开。

AI 写的异步条件变量靠谱吗?用九组测试审查等待协议
AI 生成的原创概念配图:被唤醒的任务重新经过互斥锁,再检查共享状态;图像不是精确的 API 时序图。

适用范围:单个 Node.js 进程内、同一 JavaScript agent 上的协作式异步任务。以下九段均为完整的 .mjs 文件,只依赖 Node 内置模块,无自建公共文件或第三方依赖;重复放入小型实现是为了让每段都可以单独复制运行。实测环境为 Node.js v24.19.0,命令为 node --unhandled-rejections=strict 文件名.mjs。文中的错误版本被设计为能够收尾的反例,不会把测试进程永久挂起。第七、八节直接测试单次 wait 的取消契约,业务消费流程仍应使用谓词循环。

先写契约:检查和修改谓词都在同一把互斥锁下完成;调用 wait 时持锁,挂起期间不持锁,正常返回或取消抛错时重新持锁;通知不是资源,也不是成功凭证;任何被唤醒的调用方都应循环检查业务谓词。本文实现和测试为原创教学代码,官方文档用于核对 JavaScript 与 Node 的基础行为,并不代表官方提供或认证这个条件变量。

一、先让错误版本稳定丢一次通知

审查 AI 代码时,我先要求它给出一条失败时序,而不是解释代码为什么看起来正确。条件变量没有业务状态,也不保存未来可兑换的通知。真正需要持久保存的是队列长度、关闭标志或版本号;这些状态共同决定一个布尔表达式,这个表达式就是谓词。通知只是提醒等待者重新查看它。
下面故意实现错误的等待:先释放互斥锁,再跨过一个事件循环检查点,最后登记等待者。生产者已经排在锁队列中,因此它能在这个空隙修改状态并发出通知。我们不靠毫秒计时碰运气,而是明确安排交错,再用一个事件循环检查点观察结果。最后额外通知仅用于收尾,不能被当作修复。

独立文件:01-lost-wakeup.mjs

import assert from "node:assert/strict";

class Mutex {
  #busy = false;
  #queue = [];
  async lock() {
    const guard = { mutex: this, release: null };
    await this.relock(guard);
    return guard;
  }
  async relock(guard) {
    if (guard.mutex !== this || guard.release !== null)
      throw new Error("invalid guard");
    if (this.#busy) {
      await new Promise(resolve => this.#queue.push(resolve));
    } else {
      this.#busy = true;
    }
    let used = false;
    guard.release = () => {
      if (used) throw new Error("already released");
      used = true;
      guard.release = null;
      const next = this.#queue.shift();
      if (next) next();
      else this.#busy = false;
    };
  }
}

const mutex = new Mutex();
const waiters = [];
let ready = false;
let resumed = false;
const notify = () => waiters.shift()?.();
async function brokenWait(guard) {
  guard.release();
  await new Promise(resolve => setImmediate(resolve)); // Deliberate gap.
  await new Promise(resolve => waiters.push(resolve));
  await mutex.relock(guard);
}
const guard = await mutex.lock();
const producer = (async () => {
  const g = await mutex.lock();
  try { ready = true; notify(); }
  finally { g.release(); }
})();
const consumer = brokenWait(guard).then(() => {
  resumed = true;
  guard.release();
});
await producer;
await new Promise(resolve => setImmediate(resolve));
assert.equal(ready, true);
assert.equal(resumed, false);
assert.equal(waiters.length, 1);
console.log("ready=true resumed=false pending=1");
notify(); // Test cleanup, not a protocol repair.
await consumer;

运行输出:

ready=true resumed=false pending=1

这个反例的危险在于,状态已经满足,消费者却还在睡眠。如果代码只是少发了通知,增加通知次数似乎有用;如果根因是登记与解锁之间存在空隙,重试和定时轮询只是在掩盖协议漏洞。评审时应逐个找出 wait 前半段的 await、可调用用户函数以及可能的同步重入点。

二、最小可审查实现:先看谓词,再决定要不要等

下面给出本文统一使用的实现。Mutex 只为演示协议服务;guard 是一段持锁资格,释放后 release 变为 null,重新获取后安装新的释放函数。每个 guard 只能由一个异步流程独占使用,不能复制、并行复用或自行修改。Condition 固定关联一把锁,等待和通知都要传入这把锁的有效 guard。
wait 的关键顺序是登记等待者、安装取消监听、释放锁,然后才第一次 await。这里的原子性是同一个 JavaScript agent 内部、没有用户回调重入的协作式原子性,不是跨线程机器指令,也不适用于多个 Worker 共同修改 SharedArrayBuffer。底层锁不会运行用户回调,Promise 的延续也不会在 resolve 调用栈中立即执行。

独立文件:02-predicate.mjs

import assert from "node:assert/strict";

class Mutex {
  #busy = false;
  #queue = [];
  async lock() {
    const guard = { mutex: this, release: null };
    await this.relock(guard);
    return guard;
  }
  async relock(guard) {
    if (guard.mutex !== this || guard.release !== null)
      throw new Error("invalid guard");
    if (this.#busy) {
      await new Promise(resolve => this.#queue.push(resolve));
    } else {
      this.#busy = true;
    }
    let used = false;
    guard.release = () => {
      if (used) throw new Error("already released");
      used = true;
      guard.release = null;
      const next = this.#queue.shift();
      if (next) next();
      else this.#busy = false;
    };
  }
}

class Condition {
  #waiters = new Set();
  constructor(mutex) { this.mutex = mutex; }
  get pending() { return this.#waiters.size; }
  check(guard) {
    if (guard.mutex !== this.mutex || !guard.release)
      throw new Error("hold the associated mutex first");
  }
  async wait(guard, signal) {
    this.check(guard);
    signal?.throwIfAborted();
    let resolveGate;
    const gate = new Promise(resolve => { resolveGate = resolve; });
    let settled = false;
    const finish = result => {
      if (settled) return;
      settled = true;
      this.#waiters.delete(wake);
      signal?.removeEventListener("abort", onAbort);
      resolveGate(result);
    };
    const wake = () => finish({ aborted: false });
    const onAbort = () => finish({ aborted: true, reason: signal.reason });
    this.#waiters.add(wake);
    signal?.addEventListener("abort", onAbort, { once: true });
    // Registration and release have no await between them.
    guard.release();
    const result = await gate;
    // Reacquisition is deliberately not cancellable.
    await this.mutex.relock(guard);
    if (result.aborted) throw result.reason;
  }
  notifyOne(guard) {
    this.check(guard);
    this.#waiters.values().next().value?.();
  }
  notifyAll(guard) {
    this.check(guard);
    for (const wake of [...this.#waiters]) wake();
  }
}
const turn = () => new Promise(resolve => setImmediate(resolve));

const mutex = new Mutex();
const changed = new Condition(mutex);
let ready = false;
const writer = await mutex.lock();
ready = true;
changed.notifyOne(writer); // No waiter: the notification is discarded.
writer.release();
const reader = await mutex.lock();
try {
  while (!ready) await changed.wait(reader);
  assert.equal(changed.pending, 0);
  console.log("predicate=true; no wait needed");
} finally { reader.release(); }

运行输出:

predicate=true; no wait needed

这段测试先通知,后启动读取方,仍然完成,因为读取方检查的是 ready,不是有没有收到历史通知。条件变量不是信号量,也不是消息队列;如果业务需要保存每一次事件,就应保存计数或数据,再用相应谓词等待。本文不声称这个小实现是可直接发布的通用库,尤其不支持锁重入、获取锁时取消、跨线程共享或恶意篡改 guard。

三、验证登记与释放之间没有通知空隙

只有给出正确路径的可运行测试,才算真正修复了第一节的问题。这里继续让生产者先排队抢锁;消费者仍在持锁状态下检查谓词,随后调用 wait。等待节点已经存在,锁才交给生产者。因此生产者发出的通知可以命中等待节点。读取方返回时还会在同一把锁下再次检查谓词。
不要把 wait 写成先调用一个异步辅助函数准备节点,再释放锁;也不要在解锁之后才把 Promise 的 resolver 加入集合。一个表面上无害的 await 会把协议拆成两个可交错的阶段。抽象接口能否保证这一点,比函数有多少行更重要。

独立文件:03-atomic.mjs

import assert from "node:assert/strict";

class Mutex {
  #busy = false;
  #queue = [];
  async lock() {
    const guard = { mutex: this, release: null };
    await this.relock(guard);
    return guard;
  }
  async relock(guard) {
    if (guard.mutex !== this || guard.release !== null)
      throw new Error("invalid guard");
    if (this.#busy) {
      await new Promise(resolve => this.#queue.push(resolve));
    } else {
      this.#busy = true;
    }
    let used = false;
    guard.release = () => {
      if (used) throw new Error("already released");
      used = true;
      guard.release = null;
      const next = this.#queue.shift();
      if (next) next();
      else this.#busy = false;
    };
  }
}

class Condition {
  #waiters = new Set();
  constructor(mutex) { this.mutex = mutex; }
  get pending() { return this.#waiters.size; }
  check(guard) {
    if (guard.mutex !== this.mutex || !guard.release)
      throw new Error("hold the associated mutex first");
  }
  async wait(guard, signal) {
    this.check(guard);
    signal?.throwIfAborted();
    let resolveGate;
    const gate = new Promise(resolve => { resolveGate = resolve; });
    let settled = false;
    const finish = result => {
      if (settled) return;
      settled = true;
      this.#waiters.delete(wake);
      signal?.removeEventListener("abort", onAbort);
      resolveGate(result);
    };
    const wake = () => finish({ aborted: false });
    const onAbort = () => finish({ aborted: true, reason: signal.reason });
    this.#waiters.add(wake);
    signal?.addEventListener("abort", onAbort, { once: true });
    // Registration and release have no await between them.
    guard.release();
    const result = await gate;
    // Reacquisition is deliberately not cancellable.
    await this.mutex.relock(guard);
    if (result.aborted) throw result.reason;
  }
  notifyOne(guard) {
    this.check(guard);
    this.#waiters.values().next().value?.();
  }
  notifyAll(guard) {
    this.check(guard);
    for (const wake of [...this.#waiters]) wake();
  }
}
const turn = () => new Promise(resolve => setImmediate(resolve));

const mutex = new Mutex();
const changed = new Condition(mutex);
let ready = false;
const reader = await mutex.lock();
const producer = (async () => {
  const writer = await mutex.lock();
  try {
    assert.equal(changed.pending, 1);
    ready = true;
    changed.notifyOne(writer);
  } finally { writer.release(); }
})();
try {
  while (!ready) await changed.wait(reader);
  assert.equal(changed.pending, 0);
  console.log("registered-before-release; ready=true");
} finally { reader.release(); }
await producer;

运行输出:

registered-before-release; ready=true

这里先登记、后释放,并不意味着等待者在持锁时阻塞线程。wait 只把异步函数挂起,生产者可以继续运行。需要同时成立的是三个条件:谓词在锁内检查,状态在同一把锁内修改,等待登记与释放没有可交错空隙。缺少任何一项,通知代码写得再精巧也无法保证业务进展。

四、为什么必须使用 while,而不是 if

即使这个 Promise 实现不会无缘无故地自己唤醒,也必须循环检查谓词。notifyAll 可以让两个消费者同时离开条件队列;它们随后分别竞争锁。第一个消费者拿走唯一的数据后,第二个消费者看到的状态又变成空队列。这不是 JavaScript 出错,而是通知从来没有承诺为每位被唤醒者预留资源。
测试先让两个消费者睡眠,再放入一个元素并广播。一个事件循环检查点之后,恰好一个消费者取得元素,另一个重新入队。最后设置关闭标志并广播,让剩余消费者有合法的退出路径。关闭同样是谓词的一部分,不能只用一次通知表达。

独立文件:04-predicate-loop.mjs

import assert from "node:assert/strict";

class Mutex {
  #busy = false;
  #queue = [];
  async lock() {
    const guard = { mutex: this, release: null };
    await this.relock(guard);
    return guard;
  }
  async relock(guard) {
    if (guard.mutex !== this || guard.release !== null)
      throw new Error("invalid guard");
    if (this.#busy) {
      await new Promise(resolve => this.#queue.push(resolve));
    } else {
      this.#busy = true;
    }
    let used = false;
    guard.release = () => {
      if (used) throw new Error("already released");
      used = true;
      guard.release = null;
      const next = this.#queue.shift();
      if (next) next();
      else this.#busy = false;
    };
  }
}

class Condition {
  #waiters = new Set();
  constructor(mutex) { this.mutex = mutex; }
  get pending() { return this.#waiters.size; }
  check(guard) {
    if (guard.mutex !== this.mutex || !guard.release)
      throw new Error("hold the associated mutex first");
  }
  async wait(guard, signal) {
    this.check(guard);
    signal?.throwIfAborted();
    let resolveGate;
    const gate = new Promise(resolve => { resolveGate = resolve; });
    let settled = false;
    const finish = result => {
      if (settled) return;
      settled = true;
      this.#waiters.delete(wake);
      signal?.removeEventListener("abort", onAbort);
      resolveGate(result);
    };
    const wake = () => finish({ aborted: false });
    const onAbort = () => finish({ aborted: true, reason: signal.reason });
    this.#waiters.add(wake);
    signal?.addEventListener("abort", onAbort, { once: true });
    // Registration and release have no await between them.
    guard.release();
    const result = await gate;
    // Reacquisition is deliberately not cancellable.
    await this.mutex.relock(guard);
    if (result.aborted) throw result.reason;
  }
  notifyOne(guard) {
    this.check(guard);
    this.#waiters.values().next().value?.();
  }
  notifyAll(guard) {
    this.check(guard);
    for (const wake of [...this.#waiters]) wake();
  }
}
const turn = () => new Promise(resolve => setImmediate(resolve));

const mutex = new Mutex();
const changed = new Condition(mutex);
const items = [];
const taken = [];
let closed = false;
async function consume() {
  const g = await mutex.lock();
  try {
    while (items.length === 0 && !closed) await changed.wait(g);
    if (items.length) taken.push(items.shift());
  } finally { g.release(); }
}
const readers = [consume(), consume()];
await turn();
assert.equal(changed.pending, 2);
let g = await mutex.lock();
items.push("job");
changed.notifyAll(g);
g.release();
await turn();
assert.deepEqual(taken, ["job"]);
assert.equal(changed.pending, 1);
g = await mutex.lock();
closed = true;
changed.notifyAll(g);
g.release();
await Promise.all(readers);
console.log("consumed=1; rewaited=1; pending=0");

运行输出:

consumed=1; rewaited=1; pending=0

把 while 改成 if 之后,第二个消费者可能读到 undefined,或者在后续代码中错误地认定已有资源。循环的价值也不只在防止传统线程模型中的虚假唤醒,它还抵御广播、竞争者先消费资源以及多个业务条件共用一条等待队列。测试断言应关注资源没有被重复消费,而不是要求所有通知都立即产生业务结果。

五、notifyOne 不能替你挑选谓词成立的人

notifyOne 通常适合等待同一种条件、每次状态变化只新增一份资源的场景。若同一条件变量混合了不同谓词,它选中的等待者未必有资格前进。下面 A 等待数值至少为二,B 只等待至少为一。数值变为一时,单次通知选中了先登记的 A;A 重新睡眠,真正满足条件的 B 仍然没有机会检查。
这次没有丢失任何通知,问题在于唤醒策略与谓词集合不匹配。可以按条件拆成多个条件变量,也可以广播后让所有人依次持锁检查。广播增加调度开销,但在混合条件、关闭、批量状态切换中,往往更容易证明不会遗漏可以前进的任务。

独立文件:05-notify-policy.mjs

import assert from "node:assert/strict";

class Mutex {
  #busy = false;
  #queue = [];
  async lock() {
    const guard = { mutex: this, release: null };
    await this.relock(guard);
    return guard;
  }
  async relock(guard) {
    if (guard.mutex !== this || guard.release !== null)
      throw new Error("invalid guard");
    if (this.#busy) {
      await new Promise(resolve => this.#queue.push(resolve));
    } else {
      this.#busy = true;
    }
    let used = false;
    guard.release = () => {
      if (used) throw new Error("already released");
      used = true;
      guard.release = null;
      const next = this.#queue.shift();
      if (next) next();
      else this.#busy = false;
    };
  }
}

class Condition {
  #waiters = new Set();
  constructor(mutex) { this.mutex = mutex; }
  get pending() { return this.#waiters.size; }
  check(guard) {
    if (guard.mutex !== this.mutex || !guard.release)
      throw new Error("hold the associated mutex first");
  }
  async wait(guard, signal) {
    this.check(guard);
    signal?.throwIfAborted();
    let resolveGate;
    const gate = new Promise(resolve => { resolveGate = resolve; });
    let settled = false;
    const finish = result => {
      if (settled) return;
      settled = true;
      this.#waiters.delete(wake);
      signal?.removeEventListener("abort", onAbort);
      resolveGate(result);
    };
    const wake = () => finish({ aborted: false });
    const onAbort = () => finish({ aborted: true, reason: signal.reason });
    this.#waiters.add(wake);
    signal?.addEventListener("abort", onAbort, { once: true });
    // Registration and release have no await between them.
    guard.release();
    const result = await gate;
    // Reacquisition is deliberately not cancellable.
    await this.mutex.relock(guard);
    if (result.aborted) throw result.reason;
  }
  notifyOne(guard) {
    this.check(guard);
    this.#waiters.values().next().value?.();
  }
  notifyAll(guard) {
    this.check(guard);
    for (const wake of [...this.#waiters]) wake();
  }
}
const turn = () => new Promise(resolve => setImmediate(resolve));

const mutex = new Mutex();
const changed = new Condition(mutex);
let value = 0;
const done = [];
async function watch(name, threshold) {
  const g = await mutex.lock();
  try {
    while (value < threshold) await changed.wait(g);
    done.push(name);
  } finally { g.release(); }
}
const a = watch("A", 2);
const b = watch("B", 1);
await turn();
let g = await mutex.lock();
value = 1;
changed.notifyOne(g);
g.release();
await turn();
assert.deepEqual(done, []);
assert.equal(changed.pending, 2);
g = await mutex.lock();
changed.notifyAll(g);
g.release();
await turn();
assert.deepEqual(done, ["B"]);
g = await mutex.lock();
value = 2;
changed.notifyAll(g);
g.release();
await Promise.all([a, b]);
assert.deepEqual(done, ["B", "A"]);
console.log("notifyOne: none; notifyAll: B, then A");

运行输出:

notifyOne: none; notifyAll: B, then A

Set 的插入顺序让本文测试可预测,但不等于对业务任务提供无饥饿承诺。等待者被选中、重新加入锁队列、获得锁、谓词成立,是四个不同事件。若 AI 把先进先出等待集合描述成端到端公平性,就应要求它补充完整的调度假设与证明,而不能只看一个 shift 或一个 Set。

六、被通知之后,必须先重新获得锁

一次通知只会结束条件等待阶段。它不能让等待者绕过仍在修改共享状态的持锁者。本文 API 保证 wait 正常返回时,原来的 guard 已重新持有锁;调用方因此可以直接回到 while 检查,也能统一在 finally 中释放。
为了把这条契约变成可观察的行为,测试让通知方在广播后暂时保留锁。即使 Promise 已经完成,被通知的读取方也不能进入临界区。这里故意持锁跨过一个事件循环检查点只是测试手段,生产业务应尽量缩短持锁时间,避免把慢速网络请求放进临界区。

独立文件:06-reacquire.mjs

import assert from "node:assert/strict";

class Mutex {
  #busy = false;
  #queue = [];
  async lock() {
    const guard = { mutex: this, release: null };
    await this.relock(guard);
    return guard;
  }
  async relock(guard) {
    if (guard.mutex !== this || guard.release !== null)
      throw new Error("invalid guard");
    if (this.#busy) {
      await new Promise(resolve => this.#queue.push(resolve));
    } else {
      this.#busy = true;
    }
    let used = false;
    guard.release = () => {
      if (used) throw new Error("already released");
      used = true;
      guard.release = null;
      const next = this.#queue.shift();
      if (next) next();
      else this.#busy = false;
    };
  }
}

class Condition {
  #waiters = new Set();
  constructor(mutex) { this.mutex = mutex; }
  get pending() { return this.#waiters.size; }
  check(guard) {
    if (guard.mutex !== this.mutex || !guard.release)
      throw new Error("hold the associated mutex first");
  }
  async wait(guard, signal) {
    this.check(guard);
    signal?.throwIfAborted();
    let resolveGate;
    const gate = new Promise(resolve => { resolveGate = resolve; });
    let settled = false;
    const finish = result => {
      if (settled) return;
      settled = true;
      this.#waiters.delete(wake);
      signal?.removeEventListener("abort", onAbort);
      resolveGate(result);
    };
    const wake = () => finish({ aborted: false });
    const onAbort = () => finish({ aborted: true, reason: signal.reason });
    this.#waiters.add(wake);
    signal?.addEventListener("abort", onAbort, { once: true });
    // Registration and release have no await between them.
    guard.release();
    const result = await gate;
    // Reacquisition is deliberately not cancellable.
    await this.mutex.relock(guard);
    if (result.aborted) throw result.reason;
  }
  notifyOne(guard) {
    this.check(guard);
    this.#waiters.values().next().value?.();
  }
  notifyAll(guard) {
    this.check(guard);
    for (const wake of [...this.#waiters]) wake();
  }
}
const turn = () => new Promise(resolve => setImmediate(resolve));

const mutex = new Mutex();
const changed = new Condition(mutex);
const trace = [];
let ready = false;
const reader = (async () => {
  const g = await mutex.lock();
  try {
    while (!ready) await changed.wait(g);
    assert.equal(typeof g.release, "function");
    trace.push("reader-holds-lock");
  } finally { g.release(); }
})();
await turn();
const writer = await mutex.lock();
ready = true;
changed.notifyOne(writer);
trace.push("notified");
await turn();
assert.deepEqual(trace, ["notified"]);
trace.push("writer-release");
writer.release();
await reader;
assert.deepEqual(trace, ["notified", "writer-release", "reader-holds-lock"]);
console.log(trace.join(" -> "));

运行输出:

notified -> writer-release -> reader-holds-lock

如果 wait 只是返回内部通知 Promise,而没有等待重新获取锁,那么调用者以为自己还在临界区,实际却已失去保护。反过来,如果 wait 在持锁时等待通知,通知方又需要这把锁修改谓词,就形成自我封锁。评审中要把进入 wait 前、挂起期间、返回或抛错之后的锁所有权逐项写清楚。

七、取消不是 Promise.race:还要出队、解绑和重新持锁

给 wait 套一层 Promise.race 看似能实现超时或取消,却不会自动移除原等待节点。这个幽灵节点可能吃掉下一次 notifyOne,让真正等待的任务继续睡眠;它也会保留闭包与监听器。本文让通知和取消统一经过 finish,保证只结算一次、同步移除节点,并且在两种路径上都解绑 abort 监听。
取消发生后,wait 仍然先重新获取互斥锁,随后才抛出取消原因。这意味着取消不承诺立即返回;如果其他持锁者永不释放,取消者也无法完成。这是维持调用方锁状态契约的有意选择,不能在文档中同时承诺立即取消与必定持锁返回。

独立文件:07-cancel.mjs

import assert from "node:assert/strict";

class Mutex {
  #busy = false;
  #queue = [];
  async lock() {
    const guard = { mutex: this, release: null };
    await this.relock(guard);
    return guard;
  }
  async relock(guard) {
    if (guard.mutex !== this || guard.release !== null)
      throw new Error("invalid guard");
    if (this.#busy) {
      await new Promise(resolve => this.#queue.push(resolve));
    } else {
      this.#busy = true;
    }
    let used = false;
    guard.release = () => {
      if (used) throw new Error("already released");
      used = true;
      guard.release = null;
      const next = this.#queue.shift();
      if (next) next();
      else this.#busy = false;
    };
  }
}

class Condition {
  #waiters = new Set();
  constructor(mutex) { this.mutex = mutex; }
  get pending() { return this.#waiters.size; }
  check(guard) {
    if (guard.mutex !== this.mutex || !guard.release)
      throw new Error("hold the associated mutex first");
  }
  async wait(guard, signal) {
    this.check(guard);
    signal?.throwIfAborted();
    let resolveGate;
    const gate = new Promise(resolve => { resolveGate = resolve; });
    let settled = false;
    const finish = result => {
      if (settled) return;
      settled = true;
      this.#waiters.delete(wake);
      signal?.removeEventListener("abort", onAbort);
      resolveGate(result);
    };
    const wake = () => finish({ aborted: false });
    const onAbort = () => finish({ aborted: true, reason: signal.reason });
    this.#waiters.add(wake);
    signal?.addEventListener("abort", onAbort, { once: true });
    // Registration and release have no await between them.
    guard.release();
    const result = await gate;
    // Reacquisition is deliberately not cancellable.
    await this.mutex.relock(guard);
    if (result.aborted) throw result.reason;
  }
  notifyOne(guard) {
    this.check(guard);
    this.#waiters.values().next().value?.();
  }
  notifyAll(guard) {
    this.check(guard);
    for (const wake of [...this.#waiters]) wake();
  }
}
const turn = () => new Promise(resolve => setImmediate(resolve));

import { getEventListeners } from "node:events";
const mutex = new Mutex();
const changed = new Condition(mutex);
const controller = new AbortController();
const reason = new Error("cancelled");
let caught = false;
const reader = (async () => {
  const g = await mutex.lock();
  try {
    await changed.wait(g, controller.signal);
    assert.fail("must abort");
  } catch (error) {
    assert.equal(error, reason);
    assert.equal(typeof g.release, "function");
    caught = true;
  } finally { g.release(); }
})();
await turn();
const writer = await mutex.lock();
controller.abort(reason);
assert.equal(changed.pending, 0);
assert.equal(getEventListeners(controller.signal, "abort").length, 0);
await turn();
assert.equal(caught, false); // Reacquisition is still blocked.
writer.release();
await reader;
assert.equal(caught, true);
const g = await mutex.lock();
try {
  await assert.rejects(changed.wait(g, controller.signal), error => error === reason);
  assert.equal(typeof g.release, "function");
} finally { g.release(); }
console.log("cancelled; pending=0; listeners=0; lock-restored");

运行输出:

cancelled; pending=0; listeners=0; lock-restored

已经取消的 signal 会在释放锁之前被检查,因此调用者仍持有原 guard。等待中的取消则先完成内部结果对象,再在重新持锁后抛错;内部 gate 始终兑现,避免制造无人观察的内部拒绝。不过调用者仍必须处理 wait 返回的拒绝,库不能替业务吞掉错误。取消原因可能是任意值,所以结果使用 aborted 标记区分成功与取消,不用原因的真假值判断。

八、通知与取消相撞时,必须有明确胜负规则

本文选择先结算者获胜:通知先命中节点,则这一次 wait 正常返回;取消先命中,则重新持锁后抛出原原因。节点一旦结算就立刻出队并移除监听,后来的操作不再改变这一轮结果。下面分别测试两种顺序,并把取消原因设为零,以防实现偷偷用 if(reason) 判断错误。
这个规则只定义一次条件等待,不代表整个业务任务从此不可取消。如果业务要求取消总是优先,需要在持锁后另行检查 signal,并明确如何处理已经被它占用的唤醒机会。资源仍可用而该任务选择退出时,应通知其他候选者,或选择适当的广播策略,避免把剩余任务永久留在等待队列。

独立文件:08-race.mjs

import assert from "node:assert/strict";

class Mutex {
  #busy = false;
  #queue = [];
  async lock() {
    const guard = { mutex: this, release: null };
    await this.relock(guard);
    return guard;
  }
  async relock(guard) {
    if (guard.mutex !== this || guard.release !== null)
      throw new Error("invalid guard");
    if (this.#busy) {
      await new Promise(resolve => this.#queue.push(resolve));
    } else {
      this.#busy = true;
    }
    let used = false;
    guard.release = () => {
      if (used) throw new Error("already released");
      used = true;
      guard.release = null;
      const next = this.#queue.shift();
      if (next) next();
      else this.#busy = false;
    };
  }
}

class Condition {
  #waiters = new Set();
  constructor(mutex) { this.mutex = mutex; }
  get pending() { return this.#waiters.size; }
  check(guard) {
    if (guard.mutex !== this.mutex || !guard.release)
      throw new Error("hold the associated mutex first");
  }
  async wait(guard, signal) {
    this.check(guard);
    signal?.throwIfAborted();
    let resolveGate;
    const gate = new Promise(resolve => { resolveGate = resolve; });
    let settled = false;
    const finish = result => {
      if (settled) return;
      settled = true;
      this.#waiters.delete(wake);
      signal?.removeEventListener("abort", onAbort);
      resolveGate(result);
    };
    const wake = () => finish({ aborted: false });
    const onAbort = () => finish({ aborted: true, reason: signal.reason });
    this.#waiters.add(wake);
    signal?.addEventListener("abort", onAbort, { once: true });
    // Registration and release have no await between them.
    guard.release();
    const result = await gate;
    // Reacquisition is deliberately not cancellable.
    await this.mutex.relock(guard);
    if (result.aborted) throw result.reason;
  }
  notifyOne(guard) {
    this.check(guard);
    this.#waiters.values().next().value?.();
  }
  notifyAll(guard) {
    this.check(guard);
    for (const wake of [...this.#waiters]) wake();
  }
}
const turn = () => new Promise(resolve => setImmediate(resolve));

async function race(notifyFirst) {
  const mutex = new Mutex();
  const changed = new Condition(mutex);
  const controller = new AbortController();
  let result;
  const reader = (async () => {
    const g = await mutex.lock();
    try {
      await changed.wait(g, controller.signal);
      result = "notified";
    } catch (error) {
      assert.equal(error, 0);
      result = "aborted";
    } finally { g.release(); }
  })();
  await turn();
  const writer = await mutex.lock();
  if (notifyFirst) {
    changed.notifyOne(writer);
    controller.abort(0);
  } else {
    controller.abort(0);
    changed.notifyOne(writer);
  }
  writer.release();
  await reader;
  assert.equal(changed.pending, 0);
  return result;
}
const results = [await race(true), await race(false)];
assert.deepEqual(results, ["notified", "aborted"]);
console.log(results.join(", "));

运行输出:

notified, aborted

生产级评审还应增加重复通知、重复 abort、正常完成后的监听器数量、取消大量排队任务之后的内存保留等测试。不要根据一次随机压力测试通过就宣称竞态已经消失。更有效的方法是先列出状态转换边界,再用确定性的握手或调度检查点逐一覆盖。本文的 setImmediate 用于观察当前排队的工作完成,不用于宣称固定的生产延迟。

九、最后用有界队列检查完整的等待协议

把原语放进一个真实的小组合,才能看出接口是否支持业务闭环。下面容量为一的队列分别使用 notEmpty 和 notFull:消费者等待有数据或已关闭,生产者等待有空位或已关闭。两组谓词共享同一把互斥锁,却使用不同等待集合,避免一条 notifyOne 唤醒错误类别。
关闭操作先修改持久状态,再广播两个条件变量。消费者可以排空已有数据,随后返回结束标记;生产者会拒绝继续入队。这里把 null 留作结束标记,因此只演示非 null 的数据。若业务允许任意值,应改为带 done 字段的结果对象,而不是让数据与协议标记混在一起。

独立文件:09-bounded-queue.mjs

import assert from "node:assert/strict";

class Mutex {
  #busy = false;
  #queue = [];
  async lock() {
    const guard = { mutex: this, release: null };
    await this.relock(guard);
    return guard;
  }
  async relock(guard) {
    if (guard.mutex !== this || guard.release !== null)
      throw new Error("invalid guard");
    if (this.#busy) {
      await new Promise(resolve => this.#queue.push(resolve));
    } else {
      this.#busy = true;
    }
    let used = false;
    guard.release = () => {
      if (used) throw new Error("already released");
      used = true;
      guard.release = null;
      const next = this.#queue.shift();
      if (next) next();
      else this.#busy = false;
    };
  }
}

class Condition {
  #waiters = new Set();
  constructor(mutex) { this.mutex = mutex; }
  get pending() { return this.#waiters.size; }
  check(guard) {
    if (guard.mutex !== this.mutex || !guard.release)
      throw new Error("hold the associated mutex first");
  }
  async wait(guard, signal) {
    this.check(guard);
    signal?.throwIfAborted();
    let resolveGate;
    const gate = new Promise(resolve => { resolveGate = resolve; });
    let settled = false;
    const finish = result => {
      if (settled) return;
      settled = true;
      this.#waiters.delete(wake);
      signal?.removeEventListener("abort", onAbort);
      resolveGate(result);
    };
    const wake = () => finish({ aborted: false });
    const onAbort = () => finish({ aborted: true, reason: signal.reason });
    this.#waiters.add(wake);
    signal?.addEventListener("abort", onAbort, { once: true });
    // Registration and release have no await between them.
    guard.release();
    const result = await gate;
    // Reacquisition is deliberately not cancellable.
    await this.mutex.relock(guard);
    if (result.aborted) throw result.reason;
  }
  notifyOne(guard) {
    this.check(guard);
    this.#waiters.values().next().value?.();
  }
  notifyAll(guard) {
    this.check(guard);
    for (const wake of [...this.#waiters]) wake();
  }
}
const turn = () => new Promise(resolve => setImmediate(resolve));

const mutex = new Mutex();
const notEmpty = new Condition(mutex);
const notFull = new Condition(mutex);
const items = [];
let closed = false;
async function put(value) {
  const g = await mutex.lock();
  try {
    while (items.length === 1 && !closed) await notFull.wait(g);
    if (closed) throw new Error("queue closed");
    items.push(value);
    assert.ok(items.length <= 1);
    notEmpty.notifyOne(g);
  } finally { g.release(); }
}
async function take() {
  const g = await mutex.lock();
  try {
    while (items.length === 0 && !closed) await notEmpty.wait(g);
    if (items.length === 0) return null;
    const value = items.shift();
    notFull.notifyOne(g);
    return value;
  } finally { g.release(); }
}
async function close() {
  const g = await mutex.lock();
  try {
    closed = true;
    notEmpty.notifyAll(g);
    notFull.notifyAll(g);
  } finally { g.release(); }
}
const received = [];
async function consume() {
  for (;;) {
    const value = await take();
    if (value === null) return;
    received.push(value);
  }
}
const consumers = [consume(), consume()];
await Promise.all([1, 2, 3, 4, 5, 6].map(put));
await close();
await Promise.all(consumers);
assert.deepEqual(received.sort((a, b) => a - b), [1, 2, 3, 4, 5, 6]);
assert.equal(notEmpty.pending + notFull.pending, 0);
await assert.rejects(put(7), /queue closed/);
console.log("received=1,2,3,4,5,6; closed=true; pending=0");

运行输出:

received=1,2,3,4,5,6; closed=true; pending=0

这里没有使用每隔几毫秒检查一次的轮询,也没有把所有等待者都塞进一个全局 Promise。数据、容量、关闭状态决定谁可以前进;条件变量只提供安全进入睡眠和重新检查的机会。容量约束在持锁时断言,关闭之后仍验证拒绝入队,所有消费者最终结束且等待集合归零,才构成比单次成功取值更有说服力的验收。

代码评审时,我会把哪些问题交还给 AI

第一,让它给出谓词的精确定义,并标出每一处读取与写入。第二,让它画出检查失败到登记成功之间的全部可交错点,尤其是 await 和用户回调。第三,让它说明等待期间、通知之后、取消之后分别由谁持锁。第四,让它证明 notifyOne 的候选集合与业务条件匹配,而不是把先进先出当成万能解释。第五,让它列出所有清理路径,包括正常通知、提前取消、等待中取消与两者竞态。

实际选型还要看锁的所有权验证、获取阶段取消、等待队列的规模、移除节点成本、诊断信息以及异常处理约定。本文等待集合用 Set 删除节点,锁队列用数组 shift,在大规模排队时不能据此宣称常数时间性能;也没有提供优先级、可重入或跨进程语义。这些限制不会否定教学测试,但必须阻止我们把短示例包装成已完成工程验证的生产库。

我的结论是:AI 可以快速生成异步协作原语的骨架,但验收依据应当是可解释的协议、不变式和确定性测试。把通知当作提示,把状态当作事实,把重新持锁后的谓词检查当作唯一通行证,才是审查条件变量代码时最值得坚持的边界。

核对过的官方参考

参考资料核对日期:2026 年 10 月 18 日。运行输出对应文中完整代码;这些测试展示特定交错下的行为,不声称穷尽全部调度或完成形式化证明。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。