Skip to content

Instantly share code, notes, and snippets.

@loogle18
Last active June 1, 2018 21:30
Show Gist options
  • Save loogle18/8ebf01954d7ff58e2df3fd05d6de70cb to your computer and use it in GitHub Desktop.
Save loogle18/8ebf01954d7ff58e2df3fd05d6de70cb to your computer and use it in GitHub Desktop.
const Pool = function(size) {
this.taskQueue = [];
this.workerQueue = [];
this.poolSize = size;
};
Pool.prototype.addWorkerTask = function(workerTask) {
if (this.workerQueue.length > 0) {
let workerThread = this.workerQueue.shift();
workerThread.run(workerTask);
} else {
this.taskQueue.push(workerTask);
}
};
Pool.prototype.init = function init() {
for (let i = 0 ; i < this.poolSize ; i++) {
this.workerQueue.push(new WorkerThread(this));
}
};
Pool.prototype.freeWorkerThread = function(workerThread) {
if (this.taskQueue.length > 0) {
let workerTask = this.taskQueue.shift();
workerThread.run(workerTask);
} else {
this.taskQueue.push(workerThread);
}
};
const WorkerThread = function(parentPool) {
this.parentPool = parentPool;
this.workerTask = {};
};
WorkerThread.prototype.run = function(workerTask) {
this.workerTask = workerTask;
if (this.workerTask.script != null) {
let worker = new Worker(this.workerTask.script);
worker.addEventListener('message', this.dummyCallback.bind(this));
worker.postMessage(this.workerTask.startMessage);
}
};
WorkerThread.prototype.dummyCallback = function(event) {
this.workerTask.callback(event);
this.parentPool.freeWorkerThread(this);
};
const WorkerTask = function (script, callback, msg) {
this.script = script;
this.callback = callback;
this.startMessage = msg;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment