xdl
Version:
The Expo Development Library
41 lines (39 loc) • 1.96 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Semaphore = void 0;
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
class Semaphore {
constructor() {
_defineProperty(this, "queue", []);
_defineProperty(this, "available", 1);
}
async acquire() {
if (this.available > 0) {
this.available -= 1;
return Promise.resolve(true);
}
// If there is no permit available, we return a promise that resolves once the semaphore gets
// signaled enough times that "available" is equal to one.
return new Promise(resolver => this.queue.push(resolver));
}
release() {
this.available += 1;
if (this.available > 1 && this.queue.length > 0) {
throw new Error('this.available should never be > 0 when there is someone waiting.');
} else if (this.available === 1 && this.queue.length > 0) {
// If there is someone else waiting, immediately consume the permit that was released
// at the beginning of this function and let the waiting function resume.
this.available -= 1;
const nextResolver = this.queue.shift();
if (nextResolver) {
nextResolver(true);
}
}
}
}
exports.Semaphore = Semaphore;
//# sourceMappingURL=Semaphore.js.map
;