-
Notifications
You must be signed in to change notification settings - Fork 2
/
queue.js
97 lines (83 loc) · 2.23 KB
/
queue.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
var cp = require('child_process'),
util = require('util'),
EventEmitter = require('events').EventEmitter;
var Queue = module.exports = function(numWorkers, workerModule) {
this.workerModule = workerModule;
this.workers = [];
this.waiting = [];
this.queue = [];
this.dequeued = 0;
this.enqueued = 0;
this.done = false;
this.terminated = false;
this.callback = null;
for (var i = 0; i < numWorkers; i++) {
this.addWorker();
}
};
util.inherits(Queue, EventEmitter);
Queue.prototype.addWorker = function() {
var self = this;
var worker = cp.fork(this.workerModule);
this.workers.push(worker);
worker.on('message', function(m) {
self.handleMessage(m, worker);
});
worker.on('exit', function(code, signal) {
self.emit('error', 'error: worker '+worker.pid+' exited with code = '+code+', signal = '+signal);
});
};
Queue.prototype.enqueue = function(val) {
++this.enqueued;
this.queue.unshift(val);
this.emit('enqueued', val);
this.flush();
};
Queue.prototype.concat = function(array) {
this.enqueued += array.length;
if (array.length) {
this.queue = array.concat(this.queue);
}
this.emit('concat', array);
this.flush();
};
Queue.prototype.flush = function() {
var worker = null,
val = null;
this.emit('flush');
while (this.waiting.length && this.queue.length) {
worker = this.waiting.pop();
val = this.queue.pop();
++this.dequeued;
this.emit('dequeued', val);
worker.send(val);
}
};
Queue.prototype.handleMessage = function(message, worker) {
if (this.terminated) return;
if (message !== 'next') return this.emit('msg', message);
// message = 'next'
var remaining = this.queue.length;
this.waiting.push(worker);
this.flush();
if (!remaining && this.waiting.length == this.workers.length && this.done) {
//if (!this.queue.length && this.done) {
this.killWorkers();
if (this.callback) this.callback();
}
};
Queue.prototype.end = function(callback) {
if (this.queue.length) {
this.done = true;
this.callback = callback;
} else {
this.killWorkers();
if (callback) callback();
}
};
Queue.prototype.killWorkers = function() {
this.workers.forEach(function(worker) {
worker.disconnect();
});
this.terminated = true;
}