Switch to poolifier worker threads pool implementation.
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerStaticPool.ts
CommitLineData
a4624c96
JB
1import { FixedThreadPool, FixedThreadPoolOptions } from 'poolifier';
2
3import Constants from '../utils/Constants';
4import Utils from '../utils/Utils';
5import { WorkerData } from '../types/Worker';
6import Wrk from './Wrk';
7import { threadId } from 'worker_threads';
8
9export default class WorkerStaticPool extends Wrk {
10 private pool: StaticPool;
11
12 /**
13 * Create a new `WorkerStaticPool`.
14 *
15 * @param {string} workerScript
16 */
17 constructor(workerScript: string, numThreads: number) {
18 super(workerScript);
19 this.pool = StaticPool.getInstance(numThreads, this.workerScript);
20 }
21
22 get size(): number {
23 return this.pool.workers.length;
24 }
25
26 get maxElementsPerWorker(): number {
27 return 1;
28 }
29
30 /**
31 *
32 * @return {Promise<void>}
33 * @public
34 */
35 // eslint-disable-next-line @typescript-eslint/no-empty-function
36 public async start(): Promise<void> { }
37
38 /**
39 *
40 * @return {Promise<void>}
41 * @public
42 */
43 public async addElement(elementData: WorkerData): Promise<void> {
44 await this.pool.execute(elementData);
45 // Start worker sequentially to optimize memory at startup
46 await Utils.sleep(Constants.START_WORKER_DELAY);
47 }
48}
49
50class StaticPool extends FixedThreadPool<WorkerData> {
51 private static instance: StaticPool;
52
53 private constructor(numThreads: number, workerScript: string, opts?: FixedThreadPoolOptions) {
54 super(numThreads, workerScript, opts);
55 }
56
57 public static getInstance(numThreads: number, workerScript: string): StaticPool {
58 if (!StaticPool.instance) {
59 StaticPool.instance = new StaticPool(numThreads, workerScript,
60 {
61 exitHandler: (code) => {
62 if (code !== 0) {
63 console.error(`Worker ${threadId} stopped with exit code ${code}`);
64 }
65 }
66 }
67 );
68 }
69 return StaticPool.instance;
70 }
71}