| 1 | import Configuration from '../utils/Configuration'; |
| 2 | import Pool from 'worker-threads-pool'; |
| 3 | import WorkerData from '../types/WorkerData'; |
| 4 | import Wrk from './Worker'; |
| 5 | |
| 6 | export default class WorkerPool extends Wrk { |
| 7 | private pool: Pool; |
| 8 | |
| 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 | } |
| 18 | |
| 19 | get size(): number { |
| 20 | return this.pool.size; |
| 21 | } |
| 22 | |
| 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 | }); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | class UniquePool { |
| 49 | private static instance: Pool; |
| 50 | |
| 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; |
| 58 | } |
| 59 | } |