Skip to content

Instantly share code, notes, and snippets.

@calvinmetcalf
Created August 14, 2013 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calvinmetcalf/6234865 to your computer and use it in GitHub Desktop.
Save calvinmetcalf/6234865 to your computer and use it in GitHub Desktop.
further Workers
//if your workers are in an array called workers
//and your data in one called data
//this assumes wokers return promises
//that is not the case but it simplifies stuff here
//it's based on stuff from my library catiline where
//workers DO return promises.
var numIdle = workers.length;
var idle = [];
var queueLen = data.length;
var i = -1;
while(++i<numIdle){
idle[i]=i;
}
function done(num) {
var data;
if (queueLen) {
datum = data.shift();
queueLen--;
workers[num].postMessage(datum).then(function (d) {
done(num);
}, function (d) {
done(num);
});
}
else {
numIdle++;
idle.push(num);
}
}
function addData(datum){
if (!queueLen && numIdle) {
num = idle.pop();
numIdle--;
workers[num].postMessage(datum).then(function (d) {
done(num);
}, function (d) {
done(num);
});
}
else if (queueLen || !numIdle) {
queueLen = data.push(data);
}
}
var num,item;
while(numIdle&&queueLen){
num = idle.pop();
numIdle--;
item = data.unshift();
queueLen--;
workers[num].postMessage(item).then(function(d){
done(num);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment