Files
shaka-player/lib/util/mutex.js
T
Theodore Abshire aded252e40 feat(offline): Make segment storage stateless.
This refactors the storage mechanism so that the method that
attaches a segment to the manifest is be a stateless async method,
and no longer needs to be in the same session as the method that
stored the manifest.
This is the end of phase one of the work towards allowing Shaka
Player to use background fetch to store assets offline.
This change will allow a service worker to store the segments as
they are downloaded, without having to keep the Shaka Player
instance alive.

Issue #879

Change-Id: I6a3545c57bacaf7229fe8c32669e88c6cc4e4138
2021-09-07 17:05:46 +00:00

53 lines
1.1 KiB
JavaScript

/*! @license
* Shaka Player
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shaka.util.Mutex');
/**
* @summary A simple mutex.
*/
shaka.util.Mutex = class {
/** Creates the mutex. */
constructor() {
/** @private {!Array.<function()>} */
this.waiting_ = [];
/** @private {number} */
this.nextMutexId_ = 0;
/** @private {number} */
this.acquiredMutexId_ = 0;
}
/** @return {!Promise.<number>} mutexId */
async acquire() {
const mutexId = ++this.nextMutexId_;
if (!this.acquiredMutexId_) {
this.acquiredMutexId_ = mutexId;
} else {
await (new Promise((resolve, reject) => {
this.waiting_.push(() => {
this.acquiredMutexId_ = mutexId;
resolve();
});
}));
}
return mutexId;
}
/** @param {number} mutexId */
release(mutexId) {
if (mutexId == this.acquiredMutexId_) {
this.acquiredMutexId_ = 0;
if (this.waiting_.length > 0) {
const callback = this.waiting_.shift();
callback();
}
}
}
};