You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1007 B

4 years ago
  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 = this.waiters.pop();
  43. callback();
  44. }
  45. }
  46. }
  47. }
  48. module.exports = Semaphore;