1 import Configuration from
'../utils/Configuration';
2 import Pool from
'worker-threads-pool';
3 import { Worker
} from
'worker_threads';
4 import WorkerData from
'../types/WorkerData';
6 export default class Wrk
{
7 private _workerScript
: string;
8 private _workerData
: WorkerData
;
10 private _concurrentWorkers
: number;
15 * @param {string} workerScript
16 * @param {WorkerData} workerData
17 * @param {number} numConcurrentWorkers
19 constructor(workerScript
: string, workerData
: WorkerData
, numConcurrentWorkers
: number) {
20 this._workerData
= workerData
;
21 this._workerScript
= workerScript
;
22 if (Configuration
.useWorkerPool()) {
23 this._concurrentWorkers
= Configuration
.getWorkerPoolSize();
24 this._pool
= new Pool({ max
: Configuration
.getWorkerPoolSize() });
26 this._concurrentWorkers
= numConcurrentWorkers
;
34 public get
concurrentWorkers(): number {
35 return this._concurrentWorkers
;
43 async start(): Promise
<unknown
> {
44 if (Configuration
.useWorkerPool()) {
45 return this._startWorkerWithPool();
47 return this._startWorker();
55 private async _startWorkerWithPool() {
56 return new Promise((resolve
, reject
) => {
57 this._pool
.acquire(this._workerScript
, { workerData
: this._workerData
}, (err
, worker
) => {
61 worker
.once('message', resolve
);
62 worker
.once('error', reject
);
72 private async _startWorker() {
73 return new Promise((resolve
, reject
) => {
74 const worker
= new Worker(this._workerScript
, { workerData
: this._workerData
});
75 worker
.on('message', resolve
);
76 worker
.on('error', reject
);
77 worker
.on('exit', (code
) => {
79 reject(new Error(`Worker stopped with exit code ${code}`));