-
Notifications
You must be signed in to change notification settings - Fork 1
/
executor.js
37 lines (37 loc) · 1.23 KB
/
executor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'use strict';
const { Worker } = require('worker_threads');
const workerPATH = module.filename.replace('executor.js', 'worker.js');
module.exports = class WorkerPool {
constructor(size = 0) {
this.workers = [];
this.allowSpawn = false;
for (let n = 0; n < size; n++) this.workers.push(new Worker(workerPATH));
}
run(fn, ...args) {
if (this.workers.length === 0 && !this.allowSpawn) {
const promise = new Promise((resolve, reject) =>
reject(new Error('Pool size exceeded')));
return { promise };
}
const fromPool = (this.workers.length !== 0);
const worker = fromPool ? this.workers.pop() : new Worker(workerPATH);
worker.postMessage([fn.toString(), ...args]);
let done = false;
const promise = new Promise((resolve, reject) => {
worker.on('message', msg => {
done = true;
fromPool ? this.workers.push(worker) : worker.terminate();
msg.error ? reject(msg.error) : resolve(msg.result);
});
});
const cancel = () => {
if (!done) {
done = true;
worker.terminate();
if (fromPool) this.workers.push(new Worker(workerPATH));
return true;
} else { return false; }
};
return { promise, cancel };
}
};