Skip to content

Commit

Permalink
fix: concurrency limit is not set correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
mohasarc committed Apr 23, 2024
1 parent 465ca2c commit ef7437f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/ProcessingPriorityQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ export default class ProcessingPriorityQueue {
this.process();
}

if (this.currentConcurrencyCount <= this.concurrencyLimit && this.priorityQueue.size > 0) {
if (this.currentConcurrencyCount < this.concurrencyLimit && this.priorityQueue.size > 0) {
this.currentConcurrencyCount++;

const {value: sqItem, valid} = this.poll();
Expand Down
34 changes: 34 additions & 0 deletions tests/unit/PTask.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -685,4 +685,38 @@ describe("PriorityTask", () => {
});
expect(PTask.getAllPTasks("krombopulos").length).toBe(1);
});

it("should not schedule more than concurrencyLimit items", (done) => {
const CONCURRENCY_LIMIT = 2;
PTask.setConcurrencyLimit(CONCURRENCY_LIMIT);

const delayedOnRun = async (a: number) => {
await new Promise((resolve) => setTimeout(resolve, 100));
return a;
};

// Prepare tasks
const ptasks = Array.from({ length: CONCURRENCY_LIMIT + 1 }).map((_, i) => {
return new PTask<number, number>({
priority: i,
args: i,
onRun: delayedOnRun,
});
});

// run all tasks
const promises = ptasks.map((ptask) => ptask.run());

setTimeout(() => {
const runningTasks = PTask.getAllPTasks().filter((ptask) => ptask.status === "running");
const pendingTasks = PTask.getAllPTasks().filter((ptask) => ptask.status === "pending");

expect(runningTasks.length).toBe(CONCURRENCY_LIMIT);
expect(pendingTasks.length).toBe(1);

Promise.all(promises).then(() => {
done()
});
}, 10);
})
});

0 comments on commit ef7437f

Please sign in to comment.