Last active
August 29, 2015 14:05
-
-
Save sTiLL-iLL/10298f2bbabcf81f433b to your computer and use it in GitHub Desktop.
simple and effective object / worker / connection pool implimentation in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function PoolFactory() { | |
var createPool = function (options) { | |
var wrkrs = [], freeWrkrs = [], | |
opts = options || {}, | |
wCnt = options.maxWorkers || 4, | |
wrkrPth = options.path || 'whateveryouwant.js'; | |
var wp = function () { | |
for (var i = 0; i < wCnt; ++i) { | |
var w = new Worker(pth); | |
workers.push(w); | |
freeWrkrs.push(w); | |
} | |
// get a ready worker | |
function getWrkr() { | |
if (freeWrkrs.length === 0) { | |
throw new error('No workers left!'); | |
} | |
return freeWrkrs.pop(); | |
}; | |
// put back worker | |
function freeUpWrkr(worker) { | |
freeWrkrs.push(worker); | |
}; | |
// kill'em all, then yourself | |
function dispoz() { | |
var i = 0, | |
self = this, | |
cnt = workers.length; | |
function exMe() { | |
workers.forEach(function (w) { | |
w.terminate(); | |
i++; | |
if (i >= cnt) { | |
return kill(); | |
} | |
}); | |
function kill() { | |
return (self = null); | |
}; | |
}; | |
return exMe(); | |
}; | |
this.enlist = get; | |
this.dispose = dispoz; | |
this.release = freeUpWrkr; | |
}; | |
return wp; | |
} | |
this.create = createPool; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment