Last active
April 22, 2020 03:05
-
-
Save creationix/2a3277a0ddedd7bd833b36ec245bab85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const locks = {}; | |
/** | |
* @param {string} name the thing we want to have access to | |
*/ | |
async function getLock(name) { | |
while (locks[name]) await locks[name] | |
let release; | |
locks[name] = new Promise(resolve => { | |
release = () => { | |
delete locks[name]; | |
resolve(); | |
}; | |
}); | |
return { release } | |
} | |
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); | |
async function unsafeWork(key) { | |
// Simulate doing work | |
console.log(key, "Start"); | |
await sleep(100); | |
console.log(key, "End"); | |
} | |
async function safeWork(key) { | |
const lock = await getLock(key); | |
await unsafeWork(key); | |
lock.release(); | |
} | |
// | |
safeWork(1); | |
safeWork(2); | |
safeWork(1); | |
safeWork(2); | |
safeWork(3); | |
safeWork(3); | |
safeWork(1); |
Author
creationix
commented
Apr 22, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment