X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=lib%2Fworkers.js;h=405cb3858f212a1f96fefbedf1e2677e158358bf;hb=cf9aa6c3340ad00792aa3c5e1a9d047cd0140fc2;hp=ee03778d47d603711ee16e6b994e5955a49855d7;hpb=766e51a0c50e4aadad5f8c65a2b6689d91ba75d8;p=poolifier.git diff --git a/lib/workers.js b/lib/workers.js index ee03778d..405cb385 100644 --- a/lib/workers.js +++ b/lib/workers.js @@ -1,7 +1,5 @@ 'use strict' -const { - isMainThread, parentPort -} = require('worker_threads') +const { isMainThread, parentPort } = require('worker_threads') const { AsyncResource } = require('async_hooks') /** @@ -15,21 +13,27 @@ class ThreadWorker extends AsyncResource { constructor (fn, opts) { super('worker-thread-pool:pioardi') this.opts = opts || {} - this.maxInactiveTime = this.opts.maxInactiveTime || (1000 * 60) + this.maxInactiveTime = this.opts.maxInactiveTime || 1000 * 60 + this.async = !!this.opts.async 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), this.maxInactiveTime / 2) + this.interval = setInterval( + this._checkAlive.bind(this), + this.maxInactiveTime / 2 + ) this._checkAlive.bind(this)() } - parentPort.on('message', (value) => { + parentPort.on('message', value => { 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.data) - this.parent.postMessage({ data: res, _id: value._id }) - this.lastTask = Date.now() + if (this.async) { + this.runInAsyncScope(this._runAsync.bind(this), this, fn, value) + } else { + 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 @@ -37,15 +41,39 @@ 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) > this.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() + } + } + + _runAsync (fn, value) { + fn(value.data) + .then(res => { + 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