1 import { Worker
, WorkerOptions
} from
'worker_threads';
3 import Configuration from
'../utils/Configuration';
4 import Constants from
'../utils/Constants';
5 import Pool from
'worker-threads-pool';
6 import WorkerData from
'../types/WorkerData';
8 export default class Wrk
{
9 private _workerScript
: string;
10 private _workerData
: WorkerData
;
11 private _index
: number;
12 private _maxWorkerElements
: number;
13 private _worker
: Worker
;
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._index
= workerData
.index
;
25 this._workerScript
= workerScript
;
26 if (Configuration
.useWorkerPool()) {
27 WorkerPool
.maxConcurrentWorkers
= Configuration
.getWorkerPoolSize();
29 this._maxWorkerElements
= maxWorkerElements
;
36 public get
maxWorkerElements(): number {
37 return this._maxWorkerElements
;
45 async start(): Promise
<Worker
> {
46 if (Configuration
.useWorkerPool()) {
47 await this._startWorkerWithPool();
49 await this._startWorker();
59 addWorkerElement(workerData
: WorkerData
): void {
60 // FIXME: also forbid to add an element if the current number of elements > max number of elements
61 if (Configuration
.useWorkerPool()) {
64 this._workerData
= workerData
;
65 this._index
= workerData
.index
;
66 this._worker
.postMessage({ id
: Constants
.START_WORKER_ELEMENT
, workerData
: workerData
});
74 private async _startWorkerWithPool() {
75 return new Promise((resolve
, reject
) => {
76 WorkerPool
.acquire(this._workerScript
, { workerData
: this._workerData
}, (err
, worker
) => {
80 worker
.once('message', resolve
);
81 worker
.once('error', reject
);
82 this._worker
= worker
;
92 private async _startWorker() {
93 return new Promise((resolve
, reject
) => {
94 const worker
= new Worker(this._workerScript
, { workerData
: this._workerData
});
95 worker
.on('message', resolve
);
96 worker
.on('error', reject
);
97 worker
.on('exit', (code
) => {
99 reject(new Error(`Worker id ${this._index} stopped with exit code ${code}`));
102 this._worker
= worker
;
108 public static maxConcurrentWorkers
: number;
109 private static _instance
: Pool
;
111 private constructor() { }
113 public static getInstance(): Pool
{
114 if (!WorkerPool
._instance
) {
115 WorkerPool
._instance
= new Pool({ max
: WorkerPool
.maxConcurrentWorkers
});
117 return WorkerPool
._instance
;
120 public static acquire(filename
: string, options
: WorkerOptions
, callback
: (error
: Error | null, worker
: Worker
) => void): void {
121 WorkerPool
.getInstance().acquire(filename
, options
, callback
);