Semaphore.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. *
  10. * @param {number} available the amount available number of "tasks"
  11. * in the Semaphore
  12. */
  13. constructor(available) {
  14. this.available = available;
  15. /** @type {(function(): void)[]} */
  16. this.waiters = [];
  17. /** @private */
  18. this._continue = this._continue.bind(this);
  19. }
  20. /**
  21. * @param {function(): void} callback function block to capture and run
  22. * @returns {void}
  23. */
  24. acquire(callback) {
  25. if (this.available > 0) {
  26. this.available--;
  27. callback();
  28. } else {
  29. this.waiters.push(callback);
  30. }
  31. }
  32. release() {
  33. this.available++;
  34. if (this.waiters.length > 0) {
  35. process.nextTick(this._continue);
  36. }
  37. }
  38. _continue() {
  39. if (this.available > 0) {
  40. if (this.waiters.length > 0) {
  41. this.available--;
  42. const callback = /** @type {(function(): void)} */ (this.waiters.pop());
  43. callback();
  44. }
  45. }
  46. }
  47. }
  48. module.exports = Semaphore;