-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker_pool.js
68 lines (57 loc) · 1.62 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
function WorkerPool(numberOfWorkers, url) {
this.numberOfWorkers = numberOfWorkers;
this.workerPromises = [];
this.pool = [];
this.promises = [];
this.url = url;
this.startWorkers();
}
this.WorkerPool.prototype.startWorkers = function() {
for(var i = 0; i < this.numberOfWorkers; ++i) {
var worker = new Worker(this.url);
this.pool.push(worker);
}
};
this.WorkerPool.prototype.endWorkers = function() {
while(this.pool.length > 0) {
var worker = this.pool.pop();
worker.terminate();
}
this.pool = [];
};
this.WorkerPool.prototype.addWorkerPromise = function(workerPromise) {
this.workerPromises.push(workerPromise);
this.releaseWorkerPromise();
}
this.WorkerPool.prototype.releaseWorkerPromise = function() {
if(this.workerPromises.length > 0) {
if(this.pool.length > 0) {
var workerPromise = this.workerPromises.shift();
var worker = this.pool.shift();
var runPromise = workerPromise.run(worker);
runPromise.then(function success(worker) {
this.pool.push(worker);
this.releaseWorkerPromise();
}.bind(this));
}
}
}
function WorkerPromise() {
this.worker = null;
this.promise = null;
this.workload = null;
this.onmessage = null;
this.onerror = null;
}
this.WorkerPromise.prototype.run = function(worker) {
this.worker = worker;
this.promise = new Promise(function(resolve, reject) {
this.worker.onmessage = function(e) {
this.onmessage(e.data);
resolve(this.worker);
}.bind(this);
}.bind(this));
this.worker.onerror = this.onerror;
this.worker.postMessage(this.workload);
return this.promise;
}