Created
December 20, 2011 11:09
-
-
Save ahume/1501225 to your computer and use it in GitHub Desktop.
Example of creating a pool of Web 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
function WorkerPool(url) { | |
this.url = url; | |
this.pool = []; | |
} | |
WorkerPool.prototype.getWorker = function() { | |
var w; | |
if (this.pool.length > 0) { | |
w = this.pool.pop(); | |
} else { | |
w = new Worker(this.url); | |
} | |
return w; | |
} | |
WorkerPool.prototype.releaseWorker = function(w) { | |
this.pool.push(w); | |
} | |
// Create a new pool | |
var my_pool = new WorkerPool("fib.js"); | |
// Get a worker from the pool and use it | |
var worker = my_pool.getWorker(); | |
worker.onmessage = function(e) { | |
// Do stuff, then release worker if no longer working. | |
my_pool.releaseWorker(worker); | |
} | |
worker.postMessage("start"); |
hey Andy!
did you find any library/solution which meets your requirements?
I also found your answer on stackoverflow and it looks like I'm looking for something similiar.
http://slowfrog.blogspot.de/2011/05/taking-advantage-of-multiple-cores-with_25.html
this article seems to be very helpful
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a naive pattern for implementing pools of Web Workers, to enable re-use when used heavily. I think this is possibly beneficial for a few reasons.
This would also need to set a limit for the number of Workers and allow for queuing tasks until threads are available. Are there existing patterns/code out there for doing this well? Is this even valuable? Or am I doing it wrong?