Skip to content

Instantly share code, notes, and snippets.

@mstaicu
Last active September 12, 2020 11:36
Show Gist options
  • Select an option

  • Save mstaicu/e9c99f62f03b771cc6b25d11050e741a to your computer and use it in GitHub Desktop.

Select an option

Save mstaicu/e9c99f62f03b771cc6b25d11050e741a to your computer and use it in GitHub Desktop.
@nybblr inspired semaphore solution for limiting concurrent execution
class Semaphore {
constructor(max) {
this.tasks = [];
this.counter = max;
this.dispatch = this.dispatch.bind(this);
}
dispatch() {
if (this.counter > 0 && this.tasks.length > 0) {
this.counter--;
this.tasks.shift()();
}
}
release() {
this.counter++;
this.dispatch();
}
acquire() {
return new Promise(res => {
this.tasks.push(res);
setTimeout(this.dispatch, 100);
});
}
}
var semaphore = new Semaphore(2);
var run = (async() => {
await semaphore.acquire();
console.log('first runner');
await semaphore.acquire();
console.log('second runner');
await semaphore.acquire();
console.log('third runner');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment