Created
August 14, 2013 19:48
-
-
Save calvinmetcalf/6234865 to your computer and use it in GitHub Desktop.
further Workers
This file contains 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
//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