自定义锁
class Mutex {
private _queue: (() => void)[] = [];
private _locked = false;
async lock(): Promise<void> {
if (this._locked) {
await new Promise<void>((resolve) => this._queue.push(resolve));
}
this._locked = true;
}
unlock(): void {
if (this._queue.length > 0) {
const next = this._queue.shift();
next && next();
} else {
this._locked = false;
}
}
}
测试
const mutex = new Mutex();
async function criticalSection3() {
await mutex.lock();
try {
console.log('3进入临界区');
await new Promise((resolve) => setTimeout(resolve, 1000));
} finally {
console.log('3离开临界区');
mutex.unlock();
}
}
async function criticalSection4() {
await mutex.lock();
try {
console.log('4进入临界区');
await new Promise((resolve) => setTimeout(resolve, 500));
} finally {
console.log('4离开临界区');
mutex.unlock();
}
}
test('test5', async () => {
await Promise.all([criticalSection3(), criticalSection4()]);
});
awaitqueue
添加依赖
npm install awaitqueue
测试
import { AwaitQueue } from 'awaitqueue';
const queue = new AwaitQueue();
async function criticalSection1() {
await queue.push(async () => {
console.log('1进入临界区');
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log('1离开临界区');
});
}
async function criticalSection2() {
await queue.push(async () => {
console.log('2进入临界区');
await new Promise((resolve) => setTimeout(resolve, 500));
console.log('2离开临界区');
});
}
test('test4', async () => {
await Promise.all([criticalSection1(), criticalSection2()]);
});