Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion packages/cli/src/lib/threadpool.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// https://amagiacademy.com/blog/posts/2021-04-09/node-worker-threads-pool
// https://nodejs.org/api/async_context.html#using-asyncresource-for-a-worker-thread-pool
import { AsyncResource } from "node:async_hooks";
import { EventEmitter } from "node:events";
import { Worker } from "node:worker_threads";
Expand All @@ -25,9 +26,19 @@ class WorkerPool extends EventEmitter {
this.workerFile = workerFile;
this.workers = [];
this.freeWorkers = [];
this.tasks = [];

for (let i = 0; i < numThreads; i += 1) {
this.addNewWorker();

// Any time the kWorkerFreedEvent is emitted, dispatch
// the next task pending in the queue, if any.
this.on(kWorkerFreedEvent, () => {
if (this.tasks.length > 0) {
const { task, callback } = this.tasks.shift();
this.runTask(task, callback);
}
});
}
}

Expand Down Expand Up @@ -59,7 +70,8 @@ class WorkerPool extends EventEmitter {

runTask(task, callback) {
if (this.freeWorkers.length === 0) {
this.once(kWorkerFreedEvent, () => this.runTask(task, callback));
// No free threads, wait until a worker thread becomes free.
this.tasks.push({ task, callback });
return;
}

Expand Down
Loading