1 import Configuration from
'../utils/Configuration';
2 import Pool from
'worker-threads-pool';
3 import { Worker
} from
'worker_threads';
5 export default class Wrk
{
9 private _concurrentWorkers
: number;
14 * @param {String} workerScript
15 * @param {Object} workerData
16 * @param {Number} numConcurrentWorkers
18 constructor(workerScript
, workerData
, numConcurrentWorkers
) {
19 this._workerData
= workerData
;
20 this._workerScript
= workerScript
;
21 this._numConcurrentWorkers
= numConcurrentWorkers
;
22 if (Configuration
.useWorkerPool()) {
23 this._pool
= new Pool({ max
: Configuration
.getWorkerPoolSize() });
28 * @param {Number} numConcurrentWorkers
31 set
_numConcurrentWorkers(numConcurrentWorkers
: number) {
32 this._concurrentWorkers
= numConcurrentWorkers
;
35 get
_numConcurrentWorkers(): number {
36 return this._concurrentWorkers
;
44 async start(): Promise
<unknown
> {
45 if (Configuration
.useWorkerPool()) {
46 return this._startWorkerWithPool();
48 return this._startWorker();
56 private async _startWorkerWithPool() {
57 return new Promise((resolve
, reject
) => {
58 this._pool
.acquire(this._workerScript
, { workerData
: this._workerData
}, (err
, worker
) => {
62 worker
.once('message', resolve
);
63 worker
.once('error', reject
);
73 private async _startWorker() {
74 return new Promise((resolve
, reject
) => {
75 const worker
= new Worker(this._workerScript
, { workerData
: this._workerData
});
76 worker
.on('message', resolve
);
77 worker
.on('error', reject
);
78 worker
.on('exit', (code
) => {
80 reject(new Error(`Worker stopped with exit code ${code}`));