Semaphore.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. class Semaphore {
  7. /**
  8. * Creates an instance of Semaphore.
  9. * @param {number} available the amount available number of "tasks"
  10. * in the Semaphore
  11. */
  12. constructor(available) {
  13. this.available = available;
  14. /** @type {(function(): void)[]} */
  15. this.waiters = [];
  16. /** @private */
  17. this._continue = this._continue.bind(this);
  18. }
  19. /**
  20. * @param {function(): void} callback function block to capture and run
  21. * @returns {void}
  22. */
  23. acquire(callback) {
  24. if (this.available > 0) {
  25. this.available--;
  26. callback();
  27. } else {
  28. this.waiters.push(callback);
  29. }
  30. }
  31. release() {
  32. this.available++;
  33. if (this.waiters.length > 0) {
  34. process.nextTick(this._continue);
  35. }
  36. }
  37. _continue() {
  38. if (this.available > 0 && this.waiters.length > 0) {
  39. this.available--;
  40. const callback = /** @type {(function(): void)} */ (this.waiters.pop());
  41. callback();
  42. }
  43. }
  44. }
  45. module.exports = Semaphore;