1
0

Semaphore.js 744 B

123456789101112131415161718192021222324
  1. module.exports.create = function (resourceCount) {
  2. var queue = [];
  3. var returnAfter = function (func) {
  4. var called = 0;
  5. return function () {
  6. if (called++) { throw new Error("Function called multiple times"); }
  7. if (func) { func.apply(null, arguments); }
  8. resourceCount++;
  9. check();
  10. };
  11. };
  12. var check = function () {
  13. if (resourceCount < 0) { throw new Error("(resourceCount < 0) should never happen"); }
  14. if (resourceCount === 0 || queue.length === 0) { return; }
  15. resourceCount--;
  16. queue.shift()(returnAfter);
  17. };
  18. return {
  19. take: function (func) {
  20. queue.push(func);
  21. check();
  22. }
  23. };
  24. };