Skip to content

Instantly share code, notes, and snippets.

@creationix
Last active April 22, 2020 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creationix/2a3277a0ddedd7bd833b36ec245bab85 to your computer and use it in GitHub Desktop.
Save creationix/2a3277a0ddedd7bd833b36ec245bab85 to your computer and use it in GitHub Desktop.
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);
@creationix
Copy link
Author

1 Start
2 Start
3 Start
1 End
1 Start
2 End
2 Start
3 End
3 Start
1 End
1 Start
2 End
3 End
1 End

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment