X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=lib%2Fworkers.js;h=103061aa78b55e55625eb877f81b300239116d14;hb=a3c8691eb5bd772a43746fd5860d54a786463039;hp=8641ed9e871deafce80c0adafd5b9531443ec209;hpb=50811da2e375e78179b56fe78fd7674ad2f360fd;p=poolifier.git diff --git a/lib/workers.js b/lib/workers.js index 8641ed9e..103061aa 100644 --- a/lib/workers.js +++ b/lib/workers.js @@ -3,7 +3,6 @@ const { isMainThread, parentPort } = require('worker_threads') const { AsyncResource } = require('async_hooks') -const maxInactiveTime = 1000 * 60 /** * An example worker that will be always alive, you just need to extend this class if you want a static pool.
@@ -13,22 +12,22 @@ const maxInactiveTime = 1000 * 60 * @since 0.0.1 */ class ThreadWorker extends AsyncResource { - constructor (fn) { + constructor (fn, opts) { super('worker-thread-pool:pioardi') + this.opts = opts || {} + this.maxInactiveTime = this.opts.maxInactiveTime || (1000 * 60) this.lastTask = Date.now() if (!fn) throw new Error('Fn parameter is mandatory') // keep the worker active if (!isMainThread) { - this.interval = setInterval(this._checkAlive.bind(this), maxInactiveTime) + this.interval = setInterval(this._checkAlive.bind(this), this.maxInactiveTime / 2) this._checkAlive.bind(this)() } parentPort.on('message', (value) => { - if (value && value._id) { + if (value && value.data && value._id) { // here you will receive messages // console.log('This is the main thread ' + isMainThread) - const res = this.runInAsyncScope(fn, null, value) - this.parent.postMessage({ data: res, _id: value._id }) - this.lastTask = Date.now() + this.runInAsyncScope(this._run.bind(this), this, fn, value) } else if (value.parent) { // save the port to communicate with the main thread // this will be received once @@ -36,15 +35,27 @@ class ThreadWorker extends AsyncResource { } else if (value.kill) { // here is time to kill this thread, just clearing the interval clearInterval(this.interval) + this.emitDestroy() } }) } _checkAlive () { - if ((Date.now() - this.lastTask) > maxInactiveTime) { + if ((Date.now() - this.lastTask) > this.maxInactiveTime) { this.parent.postMessage({ kill: 1 }) } } + + _run (fn, value) { + try { + const res = fn(value.data) + this.parent.postMessage({ data: res, _id: value._id }) + this.lastTask = Date.now() + } catch (e) { + this.parent.postMessage({ error: e, _id: value._id }) + this.lastTask = Date.now() + } + } } module.exports.ThreadWorker = ThreadWorker