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';
6 import Constants from
'../utils/Constants';
8 export default class Wrk
{
9 private _workerScript
: string;
10 private _workerData
: WorkerData
;
11 private _index
: number;
12 private _concurrentWorkers
: number;
13 private _worker
: Worker
;
18 * @param {string} workerScript
19 * @param {WorkerData} workerData
20 * @param {number} numConcurrentWorkers
22 constructor(workerScript
: string, workerData
: WorkerData
, numConcurrentWorkers
: number) {
23 this._workerData
= workerData
;
24 this._index
= workerData
.index
;
25 this._workerScript
= workerScript
;
26 if (Configuration
.useWorkerPool()) {
27 this._concurrentWorkers
= Configuration
.getWorkerPoolSize();
28 WorkerPool
.concurrentWorkers
= this._concurrentWorkers
;
30 this._concurrentWorkers
= numConcurrentWorkers
;
38 public get
concurrentWorkers(): number {
39 return this._concurrentWorkers
;
47 async start(): Promise
<Worker
> {
48 if (Configuration
.useWorkerPool()) {
49 this._startWorkerWithPool();
61 async startNewChargingStation(workerData
: WorkerData
, numConcurrentWorkers
: number): Promise
<void> {
62 this._workerData
= workerData
;
63 this._index
= workerData
.index
;
64 this._concurrentWorkers
= numConcurrentWorkers
;
65 this._worker
.postMessage({ id
: Constants
.START_NEW_CHARGING_STATION
, workerData
: workerData
});
73 private async _startWorkerWithPool() {
74 return new Promise((resolve
, reject
) => {
75 WorkerPool
.acquire(this._workerScript
, { workerData
: this._workerData
}, (err
, worker
) => {
79 worker
.once('message', resolve
);
80 worker
.once('error', reject
);
81 this._worker
= worker
;
91 private async _startWorker() {
92 return new Promise((resolve
, reject
) => {
93 const worker
= new Worker(this._workerScript
, { workerData
: this._workerData
});
94 worker
.on('message', resolve
);
95 worker
.on('error', reject
);
96 worker
.on('exit', (code
) => {
98 reject(new Error(`Worker id ${this._index} stopped with exit code ${code}`));
101 this._worker
= worker
;
107 public static concurrentWorkers
: number;
108 private static _instance
: Pool
;
110 private constructor() { }
112 public static getInstance(): Pool
{
113 if (!WorkerPool
._instance
|| (WorkerPool
._instance
?.size
=== WorkerPool
.concurrentWorkers
)) {
114 WorkerPool
._instance
= new Pool({ max
: WorkerPool
.concurrentWorkers
});
116 return WorkerPool
._instance
;
119 public static acquire(filename
: string, options
: WorkerOptions
, callback
: (error
: Error | null, worker
: Worker
) => void): void {
120 WorkerPool
.getInstance().acquire(filename
, options
, callback
);