Add standard deviation computation to time statistics
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerStaticPool.ts
CommitLineData
c32882b0 1import { FixedThreadPool, PoolOptions } from 'poolifier';
a4624c96 2
a4624c96 3import Utils from '../utils/Utils';
c32882b0 4import { Worker } from 'worker_threads';
fd1fdf1b 5import WorkerAbstract from './WorkerAbstract';
a4624c96 6import { WorkerData } from '../types/Worker';
a4624c96 7
fd1fdf1b 8export default class WorkerStaticPool<T> extends WorkerAbstract {
a4624c96
JB
9 private pool: StaticPool;
10
11 /**
12 * Create a new `WorkerStaticPool`.
13 *
14 * @param {string} workerScript
e71cccf3 15 * @param {number} numberOfThreads
322c9192 16 * @param {number} startWorkerDelay
a4624c96 17 */
322c9192
JB
18 constructor(workerScript: string, numberOfThreads: number, startWorkerDelay?: number) {
19 super(workerScript, startWorkerDelay);
63b19acd 20 this.pool = StaticPool.getInstance(numberOfThreads, this.workerScript);
a4624c96
JB
21 }
22
23 get size(): number {
24 return this.pool.workers.length;
25 }
26
27 get maxElementsPerWorker(): number {
85f78bc0 28 return null;
a4624c96
JB
29 }
30
31 /**
32 *
3340259a 33 * @returns {Promise<void>}
a4624c96
JB
34 * @public
35 */
36 // eslint-disable-next-line @typescript-eslint/no-empty-function
37 public async start(): Promise<void> { }
38
ded13d97
JB
39 /**
40 *
3340259a 41 * @returns {Promise<void>}
ded13d97
JB
42 * @public
43 */
44 public async stop(): Promise<void> {
45 return this.pool.destroy();
46 }
47
a4624c96
JB
48 /**
49 *
3340259a
JB
50 * @param elementData
51 * @returns {Promise<void>}
a4624c96
JB
52 * @public
53 */
8434025b 54 public async addElement(elementData: T): Promise<void> {
a4624c96
JB
55 await this.pool.execute(elementData);
56 // Start worker sequentially to optimize memory at startup
322c9192 57 await Utils.sleep(this.workerStartDelay);
a4624c96
JB
58 }
59}
60
61class StaticPool extends FixedThreadPool<WorkerData> {
62 private static instance: StaticPool;
63
63b19acd
JB
64 private constructor(numberOfThreads: number, workerScript: string, opts?: PoolOptions<Worker>) {
65 super(numberOfThreads, workerScript, opts);
a4624c96
JB
66 }
67
63b19acd 68 public static getInstance(numberOfThreads: number, workerScript: string): StaticPool {
a4624c96 69 if (!StaticPool.instance) {
63b19acd 70 StaticPool.instance = new StaticPool(numberOfThreads, workerScript,
a4624c96
JB
71 {
72 exitHandler: (code) => {
73 if (code !== 0) {
1e924543 74 console.error(`Worker stopped with exit code ${code}`);
a4624c96
JB
75 }
76 }
77 }
78 );
79 }
80 return StaticPool.instance;
81 }
82}