| 1 | import { WorkerOptions, WorkerProcessType } from '../types/Worker'; |
| 2 | |
| 3 | import Utils from '../utils/Utils'; |
| 4 | import WorkerAbstract from './WorkerAbstract'; |
| 5 | import WorkerDynamicPool from './WorkerDynamicPool'; |
| 6 | import WorkerSet from './WorkerSet'; |
| 7 | import WorkerStaticPool from './WorkerStaticPool'; |
| 8 | import { isMainThread } from 'worker_threads'; |
| 9 | |
| 10 | export default class WorkerFactory { |
| 11 | public static getWorkerImplementation<T>(workerScript: string, workerProcessType: WorkerProcessType, options?: WorkerOptions): WorkerAbstract { |
| 12 | if (!isMainThread) { |
| 13 | throw new Error('Trying to get a worker implementation outside the main thread'); |
| 14 | } |
| 15 | if (Utils.isUndefined(options)) { |
| 16 | options = {} as WorkerOptions; |
| 17 | } |
| 18 | switch (workerProcessType) { |
| 19 | case WorkerProcessType.WORKER_SET: |
| 20 | if (Utils.isUndefined(options.elementsPerWorker)) { |
| 21 | options.elementsPerWorker = 1; |
| 22 | } |
| 23 | return new WorkerSet<T>(workerScript, options.elementsPerWorker); |
| 24 | case WorkerProcessType.STATIC_POOL: |
| 25 | if (Utils.isUndefined(options.poolMaxSize)) { |
| 26 | options.poolMaxSize = 16; |
| 27 | } |
| 28 | return new WorkerStaticPool<T>(workerScript, options.poolMaxSize); |
| 29 | case WorkerProcessType.DYNAMIC_POOL: |
| 30 | if (Utils.isUndefined(options.poolMinSize)) { |
| 31 | options.poolMinSize = 4; |
| 32 | } |
| 33 | if (Utils.isUndefined(options.poolMaxSize)) { |
| 34 | options.poolMaxSize = 16; |
| 35 | } |
| 36 | return new WorkerDynamicPool<T>(workerScript, options.poolMinSize, options.poolMaxSize); |
| 37 | default: |
| 38 | return null; |
| 39 | } |
| 40 | } |
| 41 | } |