semaphore.js 748 B

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
  3. * SPDX-License-Identifier: AGPL-3.0-or-later
  4. */
  5. (function(){
  6. var Semaphore = function(max) {
  7. var counter = 0;
  8. var waiting = [];
  9. this.acquire = function() {
  10. if(counter < max) {
  11. counter++;
  12. return new Promise(function(resolve) { resolve(); });
  13. } else {
  14. return new Promise(function(resolve) { waiting.push(resolve); });
  15. }
  16. };
  17. this.release = function() {
  18. counter--;
  19. if (waiting.length > 0 && counter < max) {
  20. counter++;
  21. var promise = waiting.shift();
  22. promise();
  23. }
  24. };
  25. };
  26. // needed on public share page to properly register this
  27. if (!OCA.Files) {
  28. OCA.Files = {};
  29. }
  30. OCA.Files.Semaphore = Semaphore;
  31. })();