18.typescript资源同步控制

自定义锁

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()]);
});

/** 结果说明
3进入临界区
3离开临界区
4进入临界区
4离开临界区
*/

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()]);
  //queue.stop();//关闭队列
});

/** 结果说明
1进入临界区
1离开临界区
2进入临界区
2离开临界区
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值