컨텐츠로 건너뛰기

mutex

mutex는 하나 이상의 클래스 메서드를 동시 실행성 1로 비동기 처리하는 데코레이터입니다.

import

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();
// mutex 없이
await Promise.all([
runner.runWithoutMutex(1000, "A"),
runner.runWithoutMutex(500, "B"),
runner.runWithoutMutex(0, "C"),
]);
// mutex 사용
await Promise.all([
runner.runWithMutex(1000, "A"),
runner.runWithMutex(500, "B"),
runner.runWithMutex(0, "C"),
]);

출력:

C
B
A
A
B
C