Skip to content

Commit df026d4

Browse files
add taskQueue based on generator.
1 parent 9567780 commit df026d4

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

TaskQueue.js

+52-1
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,55 @@ class TaskQueue {
5252
this.running++;
5353
}
5454
}
55-
};
55+
};
56+
57+
58+
/*
59+
* A taskQueue based on generator which implement producer-consumer pattern.
60+
* To understand this class, you need know generator\co\producer-consumer, etc.
61+
* */
62+
"use strict";
63+
64+
const co = require('co');
65+
66+
class TaskQueue {
67+
constructor(concurrency) {
68+
this.concurrency = concurrency;
69+
this.running = 0;
70+
this.taskQueue = [];
71+
this.consumerQueue = [];
72+
this.spawnWorkers(concurrency);
73+
}
74+
75+
pushTask(task) {
76+
if (this.consumerQueue.length !== 0) {
77+
this.consumerQueue.shift()(null, task);
78+
} else {
79+
this.taskQueue.push(task);
80+
}
81+
}
82+
83+
spawnWorkers(concurrency) {
84+
const self = this;
85+
for(let i = 0; i < concurrency; i++) {
86+
co(function* () {
87+
while(true) {
88+
const task = yield self.nextTask();
89+
yield task;
90+
}
91+
});
92+
}
93+
}
94+
95+
nextTask() {
96+
return callback => {
97+
if(this.taskQueue.length !== 0) {
98+
return callback(null, this.taskQueue.shift());
99+
}
100+
101+
this.consumerQueue.push(callback);
102+
}
103+
}
104+
}
105+
106+
module.exports = TaskQueue;

0 commit comments

Comments
 (0)