1 import { FixedThreadPool
, FixedThreadPoolOptions
} 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';
8 export default class WorkerStaticPool
extends Wrk
{
9 private pool
: StaticPool
;
12 * Create a new `WorkerStaticPool`.
14 * @param {string} workerScript
16 constructor(workerScript
: string, numThreads
: number) {
18 this.pool
= StaticPool
.getInstance(numThreads
, this.workerScript
);
22 return this.pool
.workers
.length
;
25 get
maxElementsPerWorker(): number {
31 * @return {Promise<void>}
34 // eslint-disable-next-line @typescript-eslint/no-empty-function
35 public async start(): Promise
<void> { }
39 * @return {Promise<void>}
42 public async addElement(elementData
: WorkerData
): Promise
<void> {
43 await this.pool
.execute(elementData
);
44 // Start worker sequentially to optimize memory at startup
45 await Utils
.sleep(Constants
.START_WORKER_DELAY
);
49 class StaticPool
extends FixedThreadPool
<WorkerData
> {
50 private static instance
: StaticPool
;
52 private constructor(numThreads
: number, workerScript
: string, opts
?: FixedThreadPoolOptions
) {
53 super(numThreads
, workerScript
, opts
);
56 public static getInstance(numThreads
: number, workerScript
: string): StaticPool
{
57 if (!StaticPool
.instance
) {
58 StaticPool
.instance
= new StaticPool(numThreads
, workerScript
,
60 exitHandler
: (code
) => {
62 console
.error(`Worker stopped with exit code ${code}`);
68 return StaticPool
.instance
;