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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://slowfrog.blogspot.de/2011/05/taking-advantage-of-multiple-cores-with_25.html
this article seems to be very helpful