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
<T
> 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 stop(): Promise
<void> {
43 return this.pool
.destroy();
48 * @return {Promise<void>}
51 public async addElement(elementData
: T
): Promise
<void> {
52 await this.pool
.execute(elementData
);
53 // Start worker sequentially to optimize memory at startup
54 await Utils
.sleep(Constants
.START_WORKER_DELAY
);
58 class StaticPool
extends FixedThreadPool
<WorkerData
> {
59 private static instance
: StaticPool
;
61 private constructor(numThreads
: number, workerScript
: string, opts
?: FixedThreadPoolOptions
) {
62 super(numThreads
, workerScript
, opts
);
65 public static getInstance(numThreads
: number, workerScript
: string): StaticPool
{
66 if (!StaticPool
.instance
) {
67 StaticPool
.instance
= new StaticPool(numThreads
, workerScript
,
69 exitHandler
: (code
) => {
71 console
.error(`Worker stopped with exit code ${code}`);
77 return StaticPool
.instance
;