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