Skip to content

Instantly share code, notes, and snippets.

@deliro
Created January 24, 2022 09:06
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 deliro/13d46b2e2442cd9353893d001ecf6ba1 to your computer and use it in GitHub Desktop.
Save deliro/13d46b2e2442cd9353893d001ecf6ba1 to your computer and use it in GitHub Desktop.
class Semaphore {
constructor(max = 1) {
if (max < 1) { max = 1; }
this.max = max;
this.count = 0;
this.queue = [];
}
acquire() {
let promise;
if (this.count < this.max) {
promise = Promise.resolve();
} else {
promise = new Promise(resolve => {
this.queue.push(resolve);
});
}
this.count++;
return promise;
}
release() {
if (this.queue.length > 0) {
const resolve = this.queue.shift();
resolve();
}
this.count--;
}
}
@deliro
Copy link
Author

deliro commented Jan 24, 2022

also a mutex

class Mutex {
  constructor() {
    this.locking = Promise.resolve();
  }

  async acquire() {
    let releaseNext;

    const lock = new Promise((resolve) => {
      releaseNext = resolve;
    });

    const release = this.locking.then(() => releaseNext);
    this.locking = this.locking.then(() => lock);

    return release;
  }
}

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