Skip to content

Instantly share code, notes, and snippets.

@ahume
Created December 20, 2011 11:09
Show Gist options
  • Save ahume/1501225 to your computer and use it in GitHub Desktop.
Save ahume/1501225 to your computer and use it in GitHub Desktop.
Example of creating a pool of Web Workers
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");
@akovalev
Copy link

akovalev commented May 1, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment