1 import Configuration from
'../utils/Configuration';
2 import Constants from
'../utils/Constants';
3 import { Worker
} from
'worker_threads';
4 import WorkerData from
'../types/WorkerData';
5 import WorkerPool from
'./WorkerPool';
7 export default class Wrk
{
8 private static wrkInstances
: Wrk
[];
9 private workerScript
: string;
10 private workerData
: WorkerData
;
11 private worker
: Worker
;
12 private maxWorkerElements
: number;
13 private numWorkerElements
: number;
18 * @param {string} workerScript
19 * @param {WorkerData} workerData
20 * @param {number} maxWorkerElements
22 constructor(workerScript
: string, workerData
: WorkerData
, maxWorkerElements
= 1) {
23 this.workerData
= workerData
;
24 this.workerScript
= workerScript
;
25 this.maxWorkerElements
= maxWorkerElements
;
26 this.numWorkerElements
= 0;
27 if (Configuration
.useWorkerPool()) {
28 WorkerPool
.maxConcurrentWorkers
= Configuration
.getWorkerPoolMaxSize();
37 async start(): Promise
<Worker
> {
38 if (Configuration
.useWorkerPool()) {
39 await this.startWorkerPool();
41 await this.startWorker();
51 addWorkerElement(workerData
: WorkerData
): void {
52 if (Configuration
.useWorkerPool()) {
53 throw Error('Cannot add Wrk element if the worker pool is enabled');
55 if (this.numWorkerElements
>= this.maxWorkerElements
) {
56 throw Error('Cannot add Wrk element: max number of elements per worker reached');
58 this.workerData
= workerData
;
59 this.worker
.postMessage({ id
: Constants
.START_WORKER_ELEMENT
, workerData
: workerData
});
60 this.numWorkerElements
++;
68 public getWorkerPoolSize(): number {
69 if (Configuration
.useWorkerPool()) {
70 return WorkerPool
.getPoolSize();
79 private async startWorkerPool() {
80 return new Promise((resolve
, reject
) => {
81 WorkerPool
.acquire(this.workerScript
, { workerData
: this.workerData
}, (err
, worker
) => {
85 worker
.once('message', resolve
);
86 worker
.once('error', reject
);
97 private async startWorker() {
98 return new Promise((resolve
, reject
) => {
99 const worker
= new Worker(this.workerScript
, { workerData
: this.workerData
});
100 worker
.on('message', resolve
);
101 worker
.on('error', reject
);
102 worker
.on('exit', (code
) => {
104 reject(new Error(`Worker stopped with exit code ${code}`));
107 this.numWorkerElements
++;
108 this.worker
= worker
;