Commit | Line | Data |
---|---|---|
418106c8 | 1 | import Configuration from '../utils/Configuration'; |
6013bc53 | 2 | import Constants from '../utils/Constants'; |
78399acb | 3 | import Pool from 'worker-threads-pool'; |
6013bc53 | 4 | import Utils from '../utils/Utils'; |
c045d9a9 | 5 | import { WorkerData } from '../types/Worker'; |
144cabe0 | 6 | import Wrk from './Wrk'; |
78399acb | 7 | |
418106c8 JB |
8 | export default class WorkerPool extends Wrk { |
9 | private pool: Pool; | |
78399acb | 10 | |
418106c8 JB |
11 | /** |
12 | * Create a new `WorkerPool`. | |
13 | * | |
14 | * @param {string} workerScript | |
15 | */ | |
16 | constructor(workerScript: string) { | |
17 | super(workerScript); | |
18 | this.pool = UniquePool.getInstance(); | |
19 | } | |
78399acb | 20 | |
418106c8 JB |
21 | get size(): number { |
22 | return this.pool.size; | |
78399acb JB |
23 | } |
24 | ||
6013bc53 JB |
25 | get maxElementsPerWorker(): number { |
26 | return 1; | |
27 | } | |
28 | ||
418106c8 JB |
29 | /** |
30 | * | |
31 | * @return {Promise<void>} | |
32 | * @public | |
33 | */ | |
6013bc53 | 34 | // eslint-disable-next-line @typescript-eslint/no-empty-function |
418106c8 JB |
35 | public async start(): Promise<void> { } |
36 | ||
37 | /** | |
38 | * | |
6013bc53 | 39 | * @return {Promise<void>} |
418106c8 JB |
40 | * @public |
41 | */ | |
42 | public async addElement(elementData: WorkerData): Promise<void> { | |
43 | return new Promise((resolve, reject) => { | |
44 | this.pool.acquire(this.workerScript, { workerData: elementData }, (err, worker) => { | |
45 | if (err) { | |
46 | return reject(err); | |
47 | } | |
48 | worker.once('message', resolve); | |
49 | worker.once('error', reject); | |
50 | }); | |
6013bc53 JB |
51 | // Start worker sequentially to optimize memory at startup |
52 | void Utils.sleep(Constants.START_WORKER_DELAY); | |
418106c8 | 53 | }); |
78399acb | 54 | } |
418106c8 JB |
55 | } |
56 | ||
57 | class UniquePool { | |
58 | private static instance: Pool; | |
78399acb | 59 | |
418106c8 JB |
60 | private constructor() { } |
61 | ||
62 | public static getInstance(): Pool { | |
63 | if (!UniquePool.instance) { | |
64 | UniquePool.instance = new Pool({ max: Configuration.getWorkerPoolMaxSize() }); | |
65 | } | |
66 | return UniquePool.instance; | |
78399acb JB |
67 | } |
68 | } |