UNPKG

virtual-worker-pool

Version:

Virtual async workers

113 lines (89 loc) 2.71 kB
//# Virtual Thread Worker // Virtual because in Node you cannot create a true child thread, BUT since the // the event loop is so fast, you can simulate concurrent thread behavior using // async strategies. var VirtualThread = function(id) { this.id = id || 'Anon VirtualThread'; this.tout = null; // holds reference to timeout method on stack this.immediateObject = null; // holds reference to immediate method on stack this.status = 'unstarted'; // stopped, resuming, waiting, working this.statusMsg = ''; // can hold error message when error this.cycleMode = 1; // 0 - Immediate : 1 - timeOut if (this.init) { this.init(); } }; // Clear the timtout from the stack VirtualThread.prototype.clearCycle = function() { if (this.cycleMode) { clearTimeout(this.tout); } else { clearImmediate(this.immediateObject); } }; VirtualThread.prototype.cycle = function() { var self = this; //clearTimeout(self.tout); var selfArgs = arguments; if (self.status !== 'working') { self.status = 'resuming'; } if (self.cycleMode) { self.tout = setTimeout(function() { self.run(selfArgs); }, self.cycleAfterMilliseconds); } else { self.immediateObject = setImmediate(function() { self.run(selfArgs); }); } }; VirtualThread.prototype.cycleImmediate = function() { // if Worker is in immediate mode, clear it from the stack if (this.cycleMode === 1) { clearTimeout(this.tout); } // switch to timeout mode this.cycleMode = 0; // re-cycle this.cycle(); }; VirtualThread.prototype.cycleAfter = function(milliseconds) { // ensure milliseconds is an actual positive number this.cycleAfterMilliseconds = (typeof milliseconds != 'number' && milliseconds >= 0) ? 0 : milliseconds; // if Worker is in immediate mode, clear it from the stack if (this.cycleMode === 0) { clearImmediate(this.immediateObject); } // switch to timeout mode this.cycleMode = 1; // re-cycle this.cycle(); }; VirtualThread.prototype._run = function() { //...overide me }; VirtualThread.prototype.run = function() { this.clearCycle(); var selfArgs = arguments; this._run(selfArgs); }; VirtualThread.prototype.stop = function() { if (self.cycleMode) { clearTimeout(self.tout); } else { clearImmediate(self.immediateObject); } self.status = 'stopped'; }; VirtualThread.prototype.beforeStart=function(){ //... }; VirtualThread.prototype.afterStop=function(){ //... }; VirtualThread.prototype.errorJustHappened = function(errorThatJustHappened) { console.log('Error that just happened in Worker ' + errorThatJustHappened); throw errorThatJustHappened; }; module.exports = VirtualThread;