Skip to content

Instantly share code, notes, and snippets.

@nikostoulas
Created March 19, 2020 14:04
Show Gist options
  • Save nikostoulas/3133bacc5145a29efba59c8a09d5c5a1 to your computer and use it in GitHub Desktop.
Save nikostoulas/3133bacc5145a29efba59c8a09d5c5a1 to your computer and use it in GitHub Desktop.
Synchronised block of code in node.js - Example inspired by rabbit-queue implementation of prefetch
let globalPrefetch = 10;
async function changePrefetch(prefetchNum) {
await new Promise(r => setTimeout(r, 10));
globalPrefetch = prefetchNum;
}
async function subscribeToQueue(name, prefetch) {
await changePrefetch(prefetch);
await new Promise(r => setTimeout(r, 20));
console.log(`subscribing to queue ${name} with prefetch ${globalPrefetch}`);
}
let lock;
async function subscribeToQueueWithLock(name, prefetch) {
await lock;
lock = changePrefetch(prefetch).then(async () => {
await new Promise(r => setTimeout(r, 20));
console.log(`subscribing to queue ${name} with prefetch ${globalPrefetch}`);
});
}
/** The correct solution is this */
async function subscribeToQueueWithLocalLock(name, prefetch) {
let localLock;
do {
localLock = lock;
await lock;
} while (localLock !== lock);
lock = changePrefetch(prefetch).then(async () => {
await new Promise(r => setTimeout(r, 20));
console.log(`subscribing to queue ${name} with prefetch ${globalPrefetch}`);
});
}
async function subscribeToManyQueues() {
subscribeToQueueWithLocalLock('one', 1);
subscribeToQueueWithLocalLock('two', 2);
subscribeToQueueWithLocalLock('three', 3);
}
module.exports = subscribeToManyQueues;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment