Source: lib/util/mutex.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.Mutex');
  7. goog.require('shaka.log');
  8. /**
  9. * @summary A simple mutex.
  10. */
  11. shaka.util.Mutex = class {
  12. /** Constructs the mutex. */
  13. constructor() {
  14. /** @private {?string} */
  15. this.acquiredIdentifier = null;
  16. /** @private {!Array.<function()>} */
  17. this.unlockQueue = [];
  18. }
  19. /**
  20. * Acquires the mutex, as soon as possible.
  21. * @param {string} identifier
  22. * @return {!Promise}
  23. */
  24. async acquire(identifier) {
  25. shaka.log.v2(identifier + ' has requested mutex');
  26. if (this.acquiredIdentifier) {
  27. await new Promise((resolve) => this.unlockQueue.push(resolve));
  28. }
  29. this.acquiredIdentifier = identifier;
  30. shaka.log.v2(identifier + ' has acquired mutex');
  31. }
  32. /**
  33. * Releases your hold on the mutex.
  34. */
  35. release() {
  36. shaka.log.v2(this.acquiredIdentifier + ' has released mutex');
  37. if (this.unlockQueue.length > 0) {
  38. this.unlockQueue.shift()();
  39. } else {
  40. this.acquiredIdentifier = null;
  41. }
  42. }
  43. /**
  44. * Completely releases the mutex. Meant for use by the tests.
  45. */
  46. releaseAll() {
  47. while (this.acquiredIdentifier) {
  48. this.release();
  49. }
  50. }
  51. };