LendAndRegret/node_modules/es-toolkit/dist/promise/semaphore.js
2026-05-02 17:27:43 +08:00

35 lines
776 B
JavaScript

'use strict';
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
class Semaphore {
capacity;
available;
deferredTasks = [];
constructor(capacity) {
this.capacity = capacity;
this.available = capacity;
}
async acquire() {
if (this.available > 0) {
this.available--;
return;
}
return new Promise(resolve => {
this.deferredTasks.push(resolve);
});
}
release() {
const deferredTask = this.deferredTasks.shift();
if (deferredTask != null) {
deferredTask();
return;
}
if (this.available < this.capacity) {
this.available++;
}
}
}
exports.Semaphore = Semaphore;