// 线程锁
let isLock = false;
let lockList = [];
async function lock() {
  function unlock() {
    let waitFunc = lockList.shift();
    if (waitFunc) {
      waitFunc.resolve(unlock);
    } else {
      isLock = false;
    }
  }
  if (isLock) {
    return new Promise((resolve, reject) => {
      lockList.push({ resolve, reject });
    });
  } else {
    isLock = true;
    return unlock;
  }
}

 

使用:

let unlock = await lock();

//xxxxxxxxxxxxxx

unlock();

 

说明:

在使用await lock()时会等待上一个线程执行结束,代码才会往下走

 

相关文章:

  • 2021-11-11
  • 2021-07-25
  • 2021-04-14
  • 2022-12-23
  • 2022-12-23
  • 2021-11-15
  • 2021-06-01
  • 2021-04-07
猜你喜欢
  • 2021-07-13
  • 2021-12-03
  • 2021-05-08
  • 2022-12-23
  • 2021-12-05
  • 2022-12-23
相关资源
相似解决方案