1 import { DynamicThreadPool
, DynamicThreadPoolOptions
} from
'poolifier';
3 import Constants from
'../utils/Constants';
4 import Utils from
'../utils/Utils';
5 import { WorkerData
} from
'../types/Worker';
6 import Wrk from
'./Wrk';
7 import { threadId
} from
'worker_threads';
9 export default class WorkerDynamicPool
extends Wrk
{
10 private pool
: DynamicPool
;
13 * Create a new `WorkerDynamicPool`.
15 * @param {string} workerScript
17 constructor(workerScript
: string, min
: number, max
: number,) {
19 this.pool
= DynamicPool
.getInstance(min
, max
, this.workerScript
);
23 return this.pool
.workers
.length
;
26 get
maxElementsPerWorker(): number {
32 * @return {Promise<void>}
35 // eslint-disable-next-line @typescript-eslint/no-empty-function
36 public async start(): Promise
<void> { }
40 * @return {Promise<void>}
43 public async addElement(elementData
: WorkerData
): Promise
<void> {
44 await this.pool
.execute(elementData
);
45 // Start worker sequentially to optimize memory at startup
46 await Utils
.sleep(Constants
.START_WORKER_DELAY
);
50 class DynamicPool
extends DynamicThreadPool
<WorkerData
> {
51 private static instance
: DynamicPool
;
53 private constructor(min
: number, max
: number, filename
: string, opts
?: DynamicThreadPoolOptions
) {
54 super(min
, max
, filename
, opts
);
57 public static getInstance(min
: number, max
: number, filename
: string): DynamicPool
{
58 if (!DynamicPool
.instance
) {
59 DynamicPool
.instance
= new DynamicPool(min
, max
, filename
,
61 exitHandler
: (code
) => {
63 console
.error(`Worker ${threadId} stopped with exit code ${code}`);
69 return DynamicPool
.instance
;