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';
7 import { threadId
} from
'worker_threads';
9 export default class WorkerStaticPool
extends Wrk
{
10 private pool
: StaticPool
;
13 * Create a new `WorkerStaticPool`.
15 * @param {string} workerScript
17 constructor(workerScript
: string, numThreads
: number) {
19 this.pool
= StaticPool
.getInstance(numThreads
, 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 StaticPool
extends FixedThreadPool
<WorkerData
> {
51 private static instance
: StaticPool
;
53 private constructor(numThreads
: number, workerScript
: string, opts
?: FixedThreadPoolOptions
) {
54 super(numThreads
, workerScript
, opts
);
57 public static getInstance(numThreads
: number, workerScript
: string): StaticPool
{
58 if (!StaticPool
.instance
) {
59 StaticPool
.instance
= new StaticPool(numThreads
, workerScript
,
61 exitHandler
: (code
) => {
63 console
.error(`Worker ${threadId} stopped with exit code ${code}`);
69 return StaticPool
.instance
;