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 _worker
: Worker
;
16 * @param {string} workerScript
17 * @param {WorkerData} workerData
19 constructor(workerScript
: string, workerData
: WorkerData
) {
20 this._workerData
= workerData
;
21 this._workerScript
= workerScript
;
22 if (Configuration
.useWorkerPool()) {
23 WorkerPool
.maxConcurrentWorkers
= Configuration
.getWorkerPoolMaxSize();
32 async start(): Promise
<Worker
> {
33 if (Configuration
.useWorkerPool()) {
34 await this._startWorkerWithPool();
36 await this._startWorker();
46 addWorkerElement(workerData
: WorkerData
): void {
47 // FIXME: also forbid to add an element if the current number of elements > max number of elements
48 if (Configuration
.useWorkerPool()) {
51 this._workerData
= workerData
;
52 this._worker
.postMessage({ id
: Constants
.START_WORKER_ELEMENT
, workerData
: workerData
});
60 public getWorkerPoolSize(): number {
61 if (Configuration
.useWorkerPool()) {
62 return WorkerPool
.getPoolSize();
71 private async _startWorkerWithPool() {
72 return new Promise((resolve
, reject
) => {
73 WorkerPool
.acquire(this._workerScript
, { workerData
: this._workerData
}, (err
, worker
) => {
77 worker
.once('message', resolve
);
78 worker
.once('error', reject
);
79 this._worker
= worker
;
89 private async _startWorker() {
90 return new Promise((resolve
, reject
) => {
91 const worker
= new Worker(this._workerScript
, { workerData
: this._workerData
});
92 worker
.on('message', resolve
);
93 worker
.on('error', reject
);
94 worker
.on('exit', (code
) => {
96 reject(new Error(`Worker stopped with exit code ${code}`));
99 this._worker
= worker
;
106 public static maxConcurrentWorkers
: number;
107 private static _instance
: Pool
;
109 private constructor() { }
111 public static getInstance(): Pool
{
112 if (!WorkerPool
._instance
) {
113 WorkerPool
._instance
= new Pool({ max
: WorkerPool
.maxConcurrentWorkers
});
115 return WorkerPool
._instance
;
118 public static acquire(filename
: string, options
: WorkerOptions
, callback
: (error
: Error | null, worker
: Worker
) => void): void {
119 WorkerPool
.getInstance().acquire(filename
, options
, callback
);
122 public static getPoolSize(): number {
123 return WorkerPool
.getInstance().size
;