code
由于AsyncLock无法在线程间传递,所以使用事件代替线程,模拟线程间同步:
import AsyncLock from 'async-lock';
var lock = new AsyncLock();
function main() {
setTimeout(() => task(1), 1000);
setTimeout(() => task(2), 1000);
}
async function task(threadId) {
console.log('线程启动: ' + threadId);
await lock.acquire('a', async () => {
console.log(threadId + '开始工作');
await sleep(2000);
console.log(threadId + '工作完毕');
});
console.log('释放' + threadId);
}
function sleep(n) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(null);
}, n);
});
}
main();
输出是:
线程启动: 1
1开始工作
线程启动: 2
------------------2秒后.................
1工作完毕
2开始工作
释放1
------------------2秒后.................
2工作完毕
释放2