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
.getWorkerPoolSize();
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 private async _startWorkerWithPool() {
61 return new Promise((resolve
, reject
) => {
62 WorkerPool
.acquire(this._workerScript
, { workerData
: this._workerData
}, (err
, worker
) => {
66 worker
.once('message', resolve
);
67 worker
.once('error', reject
);
68 this._worker
= worker
;
78 private async _startWorker() {
79 return new Promise((resolve
, reject
) => {
80 const worker
= new Worker(this._workerScript
, { workerData
: this._workerData
});
81 worker
.on('message', resolve
);
82 worker
.on('error', reject
);
83 worker
.on('exit', (code
) => {
85 reject(new Error(`Worker stopped with exit code ${code}`));
88 this._worker
= worker
;
94 public static maxConcurrentWorkers
: number;
95 private static _instance
: Pool
;
97 private constructor() { }
99 public static getInstance(): Pool
{
100 if (!WorkerPool
._instance
) {
101 WorkerPool
._instance
= new Pool({ max
: WorkerPool
.maxConcurrentWorkers
});
103 return WorkerPool
._instance
;
106 public static acquire(filename
: string, options
: WorkerOptions
, callback
: (error
: Error | null, worker
: Worker
) => void): void {
107 WorkerPool
.getInstance().acquire(filename
, options
, callback
);