JS实现线程锁(Promise),NodeJS并发锁处理
// 线程锁 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()时会等待上一个线程执行结束,代码才会往下走
致读者:感谢你阅读本文,请随手点击右下角的推荐或分享,谢谢!