Skip to content

Commit

Permalink
Fixing memory leak when WorkerPool closes
Browse files Browse the repository at this point in the history
  • Loading branch information
czirker committed Feb 1, 2024
1 parent 0ddc6ee commit 29f8af1
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lib/stream/helper/worker-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export class WorkerPool extends EventEmitter {
workers: Worker[];
freeWorkers: Worker[];
messages: Record<string, (worker: Worker, m: any) => void>;
private onExit: (...args: any[]) => void;

constructor(
private id: string,
private task,
Expand All @@ -49,12 +51,11 @@ export class WorkerPool extends EventEmitter {
}
this.setMaxListeners(0);//(numThreads * 10);

process.on('SIGINT', () => {
this.close();
});
process.on('exit', () => {
this.onExit = () => {
this.close();
});
};
process.on('SIGINT', this.onExit);
process.on('exit', this.onExit);
}

addNewWorker(workerData: any) {
Expand Down Expand Up @@ -140,6 +141,11 @@ export class WorkerPool extends EventEmitter {
}

async close() {

// Remove event listeners to prevent memory leaks
process.removeListener('SIGINT', this.onExit);
process.removeListener('exit', this.onExit);

if (this.workers.length > 0) {
//console.log(this.id, "Worker Pool Closing", this.workers.length);
await Promise.allSettled(this.workers.map(w => {
Expand Down

0 comments on commit 29f8af1

Please sign in to comment.