1 import Configuration from
'../utils/Configuration';
2 import Constants from
'../utils/Constants';
3 import Pool from
'worker-threads-pool';
4 import Utils from
'../utils/Utils';
5 import WorkerData from
'../types/WorkerData';
6 import Wrk from
'./Wrk';
8 export default class WorkerPool
extends Wrk
{
12 * Create a new `WorkerPool`.
14 * @param {string} workerScript
16 constructor(workerScript
: string) {
18 this.pool
= UniquePool
.getInstance();
22 return this.pool
.size
;
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 return new Promise((resolve
, reject
) => {
44 this.pool
.acquire(this.workerScript
, { workerData
: elementData
}, (err
, worker
) => {
48 worker
.once('message', resolve
);
49 worker
.once('error', reject
);
51 // Start worker sequentially to optimize memory at startup
52 void Utils
.sleep(Constants
.START_WORKER_DELAY
);
58 private static instance
: Pool
;
60 private constructor() { }
62 public static getInstance(): Pool
{
63 if (!UniquePool
.instance
) {
64 UniquePool
.instance
= new Pool({ max
: Configuration
.getWorkerPoolMaxSize() });
66 return UniquePool
.instance
;