1 import { DynamicThreadPool
, PoolOptions
} from
'poolifier';
3 import Utils from
'../utils/Utils';
4 import { Worker
} from
'worker_threads';
5 import WorkerAbstract from
'./WorkerAbstract';
6 import { WorkerData
} from
'../types/Worker';
7 import { WorkerUtils
} from
'./WorkerUtils';
9 export default class WorkerDynamicPool
<T
> extends WorkerAbstract
{
10 private pool
: DynamicThreadPool
<WorkerData
>;
13 * Create a new `WorkerDynamicPool`.
18 * @param workerStartDelay
21 constructor(workerScript
: string, min
: number, max
: number, workerStartDelay
?: number, opts
?: PoolOptions
<Worker
>) {
22 super(workerScript
, workerStartDelay
);
23 opts
.exitHandler
= opts
?.exitHandler
?? WorkerUtils
.defaultExitHandler
;
24 this.pool
= new DynamicThreadPool
<WorkerData
>(min
, max
, this.workerScript
, opts
);
28 return this.pool
.workers
.length
;
31 get
maxElementsPerWorker(): number | null {
40 // eslint-disable-next-line @typescript-eslint/no-empty-function
41 public async start(): Promise
<void> {
42 // This is intentional
50 // eslint-disable-next-line @typescript-eslint/require-await
51 public async stop(): Promise
<void> {
52 return this.pool
.destroy();
61 public async addElement(elementData
: T
): Promise
<void> {
62 await this.pool
.execute(elementData
);
63 // Start worker sequentially to optimize memory at startup
64 await Utils
.sleep(this.workerStartDelay
);