Skip to content
Browse files

Document Pool.

  • Loading branch information...
1 parent 0853d1a commit c7843b974500625b48eb8c4832b538fddef4adc1 @jaredhanson committed Dec 2, 2011
Showing with 65 additions and 0 deletions.
  1. +65 −0 lib/functionpool/pool.js
View
65 lib/functionpool/pool.js
@@ -1,7 +1,39 @@
+/**
+ * Module dependencies.
+ */
var util = require('util')
, EventEmitter = require('events').EventEmitter
, Worker = require('./worker');
+
+/**
+ * `Pool` constructor.
+ *
+ * Assigns `fn` to a pool used to execute (potentially expensive) tasks. The
+ * pool has a limited size (defaulting to 5), which controls the maximum number
+ * of tasks that will be allowed to execute concurrently. After the limit has
+ * been reached, tasks will be queued and executed when prior tasks complete.
+ *
+ * `fn` must accept a `done` callback, which it must invoke with a result (or
+ * error) upon completion.
+ *
+ * Options:
+ * - `size` maximum number of tasks allowed to execute concurrently (default: 5)
+ *
+ * Examples:
+ *
+ * new Pool(function(name, done) {
+ * setTimeout(function() { done(null, 'Hello ' + name) }, 1000);
+ * });
+ *
+ * new Pool({ size: 3 }, function(x, y, done) {
+ * setTimeout(function() { done(null, x + y) }, 5000);
+ * });
+ *
+ * @param {Object} options
+ * @param {Function} fn
+ * @api public
+ */
function Pool(options, fn) {
if (typeof options == 'function') {
fn = options;
@@ -32,9 +64,29 @@ function Pool(options, fn) {
})
};
+/**
+ * Inherit from `EventEmitter`.
+ */
util.inherits(Pool, EventEmitter);
+/**
+ * Add a task to the pool.
+ *
+ * If the last argument to this method is a function, it will be called with a
+ * result (or error) when the task completes.
+ *
+ * Examples:
+ *
+ * pool.task('World');
+ *
+ * pool.task(3, 14, function(err, res) {
+ * console.log('3 + 14 = ' + res);
+ * });
+ *
+ * @param {Mixed} arguments
+ * @api public
+ */
Pool.prototype.add =
Pool.prototype.task = function() {
var args = Array.prototype.slice.call(arguments);
@@ -54,6 +106,11 @@ Pool.prototype.task = function() {
return (this._queue.length == 0) ? true : false;
}
+/**
+ * Dispatch next task to an available worker.
+ *
+ * @api private
+ */
Pool.prototype._dispatch = function() {
var self = this;
@@ -80,6 +137,11 @@ Pool.prototype._dispatch = function() {
}
}
+/**
+ * Create `count` number of workers.
+ *
+ * @api private
+ */
Pool.prototype._createWorkers = function(count) {
var array = [];
for (var i = 0; i < count; i++) {
@@ -89,4 +151,7 @@ Pool.prototype._createWorkers = function(count) {
};
+/**
+ * Expose `Pool`.
+ */
module.exports = Pool;

0 comments on commit c7843b9

Please sign in to comment.
Something went wrong with that request. Please try again.