1 import Configuration
from '../utils/Configuration.js';
2 import EventEmitter
from 'events';
3 import Pool
from 'worker-threads-pool';
4 import {Worker
} from 'worker_threads';
6 export default class Wrk
{
10 * @param {String} workerScript
11 * @param {Object} workerData
12 * @param {Number} numConcurrentWorkers
14 constructor(workerScript
, workerData
, numConcurrentWorkers
) {
15 this._workerData
= workerData
;
16 this._workerScript
= workerScript
;
17 this._numConcurrentWorkers
= numConcurrentWorkers
;
18 if (Configuration
.useWorkerPool()) {
19 this._pool
= new Pool({max
: Configuration
.getWorkerPoolSize()});
24 * @param {Number} numConcurrentWorkers
27 set _numConcurrentWorkers(numConcurrentWorkers
) {
28 if (numConcurrentWorkers
> 10) {
29 EventEmitter
.defaultMaxListeners
= numConcurrentWorkers
+ 1;
31 this._concurrentWorkers
= numConcurrentWorkers
;
34 get _numConcurrentWorkers() {
35 return this._concurrentWorkers
;
43 _startWorkerWithPool() {
44 return new Promise((resolve
, reject
) => {
45 this._pool
.acquire(this._workerScript
, {workerData
: this._workerData
}, (err
, worker
) => {
49 worker
.once('message', resolve
);
50 worker
.once('error', reject
);
61 return new Promise((resolve
, reject
) => {
62 const worker
= new Worker(this._workerScript
, {workerData
: this._workerData
});
63 worker
.on('message', resolve
);
64 worker
.on('error', reject
);
65 worker
.on('exit', (code
) => {
67 reject(new Error(`Worker stopped with exit code ${code}`));
79 if (Configuration
.useWorkerPool()) {
80 return this._startWorkerWithPool();
82 return this._startWorker();