-
-
Save FranciscoMarinho/d019ecdda5c359e4594f0011ff47506e to your computer and use it in GitHub Desktop.
Simple javascript thread pool example
This file contains hidden or 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
| 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