跳转到内容

mutex

mutex 是一个装饰器,用于将一个或多个类方法的并发执行限制为1个。

导入

import { mutex } from "@tai-kun/surrealdb/utils";

使用方法

function mutex(
target: (...args: any) => PromiseLike<any>,
context: ClassMethodDecoratorContext,
): (this: any, ...args: any) => Promise<any>;

参数

target

类方法。

context

Stage 3 类方法装饰器上下文。

返回值

并发执行限制为 1 的异步函数。

示例

下面的例子展示了使用和不使用 mutex 装饰器时异步操作执行顺序的不同:

import { mutex } from "@tai-kun/surrealdb/utils";
class Runner {
async runWithoutMutex(ms: number, value: string) {
await sleep(ms);
console.log(value);
}
@mutex
async runWithMutex(ms: number, value: string) {
await sleep(ms);
console.log(value);
}
}
const runner = new Runner();
// without mutex
await Promise.all([
runner.runWithoutMutex(1000, "A"),
runner.runWithoutMutex(500, "B"),
runner.runWithoutMutex(0, "C"),
]);
// with mutex
await Promise.all([
runner.runWithMutex(1000, "A"),
runner.runWithMutex(500, "B"),
runner.runWithMutex(0, "C"),
]);

输出:

C
B
A
A
B
C