Skip to content

Instantly share code, notes, and snippets.

@pgjones
Created August 21, 2016 20:59
Show Gist options
  • Save pgjones/c1aef24bd944796dbc785196d0ba6761 to your computer and use it in GitHub Desktop.
Save pgjones/c1aef24bd944796dbc785196d0ba6761 to your computer and use it in GitHub Desktop.
Simple javascript thread pool example
ThreadPool = function(script, size) {
this.threads = [];
this.tasks = [];
for (var ithread = 0; ithread < size; ithread++) {
this.threads.push(new lxst.FilterThread(script, this));
}
};
ThreadPool.prototype.queueTask = function(task, callback) {
const task = {task: task, callback: callback};
if (this.threads.length > 0) {
var thread = this.threads.shift();
thread.run(task);
} else {
this.tasks.push(task);
}
};
ThreadPool.prototype.afterTask = function(thread) {
if (this.tasks.length > 0) {
thread.run(this.tasks.shift());
} else {
this.threads.push(thread);
}
};
Thread = function(script, pool) {
this.worker = new Worker(script);
this.worker.addEventListener('message', this.onmessage.bind(this));
this.pool = pool;
this.callback = null;
};
Thread.prototype.run = function(task) {
this.worker.postMessage(task.task);
this.callback = task.callback;
};
Thread.prototype.onmessage = function(message) {
this.callback(message.data);
this.callback = null;
this.pool.afterTask(this);
};
var pool = new ThreaPool("script.js", 2);
pool.addTask(task, function(result) { console.log(result); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment