1 import { Worker
, WorkerOptions
} from
'worker_threads';
3 import Configuration from
'../utils/Configuration';
4 import Pool from
'worker-threads-pool';
5 import WorkerData from
'../types/WorkerData';
7 export default class Wrk
{
8 private _workerScript
: string;
9 private _workerData
: WorkerData
;
10 private _index
: number;
11 private _concurrentWorkers
: number;
16 * @param {string} workerScript
17 * @param {WorkerData} workerData
18 * @param {number} numConcurrentWorkers
20 constructor(workerScript
: string, workerData
: WorkerData
, numConcurrentWorkers
: number) {
21 this._workerData
= workerData
;
22 this._index
= workerData
.index
;
23 this._workerScript
= workerScript
;
24 if (Configuration
.useWorkerPool()) {
25 this._concurrentWorkers
= Configuration
.getWorkerPoolSize();
26 WorkerPool
.concurrentWorkers
= this._concurrentWorkers
;
28 this._concurrentWorkers
= numConcurrentWorkers
;
36 public get
concurrentWorkers(): number {
37 return this._concurrentWorkers
;
45 async start(): Promise
<unknown
> {
46 if (Configuration
.useWorkerPool()) {
47 return this._startWorkerWithPool();
49 return this._startWorker();
57 private async _startWorkerWithPool() {
58 return new Promise((resolve
, reject
) => {
59 WorkerPool
.acquire(this._workerScript
, { workerData
: this._workerData
}, (err
, worker
) => {
63 worker
.once('message', resolve
);
64 worker
.once('error', reject
);
74 private async _startWorker() {
75 return new Promise((resolve
, reject
) => {
76 const worker
= new Worker(this._workerScript
, { workerData
: this._workerData
});
77 worker
.on('message', resolve
);
78 worker
.on('error', reject
);
79 worker
.on('exit', (code
) => {
81 reject(new Error(`Worker id ${this._index} stopped with exit code ${code}`));
89 public static concurrentWorkers
: number;
90 private static _instance
: Pool
;
92 private constructor() { }
94 public static getInstance(): Pool
{
95 if (!WorkerPool
._instance
) {
96 WorkerPool
._instance
= new Pool({ max
: WorkerPool
.concurrentWorkers
});
98 return WorkerPool
._instance
;
101 public static acquire(filename
: string, options
: WorkerOptions
, callback
: (error
: Error | null, worker
: Worker
) => void): void {
102 WorkerPool
.getInstance().acquire(filename
, options
, callback
);