forked from OI-wiki/OI-wiki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker-pool.js
108 lines (88 loc) · 2.35 KB
/
worker-pool.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const { Worker } = require('worker_threads');
const Promise = require('bluebird');
class WorkerPool {
_workers = [];
_activeWorkers = [];
_queue = [];
constructor(workerPath, numOfThreads) {
this.workerPath = workerPath;
this.numOfThreads = numOfThreads;
this.init();
}
init() {
if (this.numOfThreads < 1) {
throw new Error('Number of threads should be at least 1');
}
for (let i = 0; i < this.numOfThreads; i++) {
const worker = new Worker(this.workerPath);
this._workers[i] = worker;
this._activeWorkers[i] = false;
}
}
destroy() {
for (let i = 0; i < this.numOfThreads; i++) {
if (this._activeWorkers[i]) {
throw new Error(`Thread ${i} is still working`);
}
this._workers[i].terminate();
}
}
// Check if any idle workers
checkWorkers() {
for (let i = 0; i < this.numOfThreads; i++) {
if (!this._activeWorkers[i]) {
return i;
}
}
return -1;
}
run(getData) {
return new Promise((resolve, reject) => {
const restWorkerId = this.checkWorkers();
const queueItem = {
getData,
callback: (error, result) => {
if (error) {
return reject(error);
}
return resolve(result);
}
}
// No more idle workers
if (restWorkerId === -1) {
this._queue.push(queueItem);
return null;
}
// Let idle workers run
this.runWorker(restWorkerId, queueItem);
})
}
async runWorker(workerId, queueItem) {
const worker = this._workers[workerId];
this._activeWorkers[workerId] = true;
const messageCallback = (result) => {
queueItem.callback(null, result);
cleanUp();
};
const errorCallback = (error) => {
queueItem.callback(error);
cleanUp();
};
// Clear up listeners
const cleanUp = () => {
worker.removeAllListeners('message');
worker.removeAllListeners('error');
this._activeWorkers[workerId] = false;
if (!this._queue.length) {
return null;
}
this.runWorker(workerId, this._queue.shift());
}
// create listeners
worker.once('message', messageCallback);
worker.once('error', errorCallback);
// Send data to other newly created workers
worker.postMessage(queueItem.getData);
}
}
module.exports = WorkerPool;