Update to poolifier 2.0.0-beta.6 (#10)
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerStaticPool.ts
CommitLineData
c32882b0 1import { FixedThreadPool, PoolOptions } from 'poolifier';
a4624c96
JB
2
3import Constants from '../utils/Constants';
4import Utils from '../utils/Utils';
c32882b0 5import { Worker } from 'worker_threads';
a4624c96
JB
6import { WorkerData } from '../types/Worker';
7import Wrk from './Wrk';
a4624c96 8
8434025b 9export default class WorkerStaticPool<T> extends Wrk {
a4624c96
JB
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
ded13d97
JB
38 /**
39 *
40 * @return {Promise<void>}
41 * @public
42 */
43 public async stop(): Promise<void> {
44 return this.pool.destroy();
45 }
46
a4624c96
JB
47 /**
48 *
49 * @return {Promise<void>}
50 * @public
51 */
8434025b 52 public async addElement(elementData: T): Promise<void> {
a4624c96
JB
53 await this.pool.execute(elementData);
54 // Start worker sequentially to optimize memory at startup
55 await Utils.sleep(Constants.START_WORKER_DELAY);
56 }
57}
58
59class StaticPool extends FixedThreadPool<WorkerData> {
60 private static instance: StaticPool;
61
c32882b0 62 private constructor(numThreads: number, workerScript: string, opts?: PoolOptions<Worker>) {
a4624c96
JB
63 super(numThreads, workerScript, opts);
64 }
65
66 public static getInstance(numThreads: number, workerScript: string): StaticPool {
67 if (!StaticPool.instance) {
68 StaticPool.instance = new StaticPool(numThreads, workerScript,
69 {
70 exitHandler: (code) => {
71 if (code !== 0) {
1e924543 72 console.error(`Worker stopped with exit code ${code}`);
a4624c96
JB
73 }
74 }
75 }
76 );
77 }
78 return StaticPool.instance;
79 }
80}