Created
January 30, 2011 16:55
-
-
Save matagus/803003 to your computer and use it in GitHub Desktop.
A pool of webworkers
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
// From: https://gist.github.com/605541#file_js_web_worker_pool.js | |
// Web Worker Pool | |
// size is the max number of arguments | |
function WorkerPool(size) { | |
var workers = 0, | |
jobs = []; | |
// url: the url of the worker script | |
// msg: the initial message to pass to the worker | |
// cb : the callback to recieve messages from postMessage. | |
// return true from cb to dismiss the worker and advance the queue. | |
// ctx: the context for cb.apply | |
this.queueJob = function(url, msg, cb, ctx) { | |
var job = { | |
"url": url, | |
"msg": msg, | |
"cb" : cb, | |
"ctx": ctx | |
}; | |
jobs.push(job); | |
if (workers < size) nextJob(); | |
}; | |
function nextJob() { | |
if (jobs.length) { | |
(function() { | |
var job = jobs.shift(), | |
worker = new Worker(job.url); | |
workers++; | |
worker.addEventListener('message', function(e) { | |
if (job.cb.call(job.ctx, e.data, worker)) { | |
worker.terminate(); | |
delete worker; | |
workers--; | |
nextJob(); | |
}; | |
}, false); | |
worker.postMessage(job.msg); | |
})(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment