| 1 | 'use strict' |
| 2 | const { |
| 3 | isMainThread, parentPort |
| 4 | } = require('worker_threads') |
| 5 | const { AsyncResource } = require('async_hooks') |
| 6 | |
| 7 | /** |
| 8 | * An example worker that will be always alive, you just need to extend this class if you want a static pool.<br> |
| 9 | * When this worker is inactive for more than 1 minute, it will send this info to the main thread,<br> |
| 10 | * if you are using DynamicThreadPool, the workers created after will be killed, the min num of thread will be guaranteed |
| 11 | * @author Alessandro Pio Ardizio |
| 12 | * @since 0.0.1 |
| 13 | */ |
| 14 | class ThreadWorker extends AsyncResource { |
| 15 | constructor (fn, opts) { |
| 16 | super('worker-thread-pool:pioardi') |
| 17 | this.opts = opts || {} |
| 18 | this.maxInactiveTime = this.opts.maxInactiveTime || (1000 * 60) |
| 19 | this.lastTask = Date.now() |
| 20 | if (!fn) throw new Error('Fn parameter is mandatory') |
| 21 | // keep the worker active |
| 22 | if (!isMainThread) { |
| 23 | this.interval = setInterval(this._checkAlive.bind(this), this.maxInactiveTime / 2) |
| 24 | this._checkAlive.bind(this)() |
| 25 | } |
| 26 | parentPort.on('message', (value) => { |
| 27 | if (value && value.data && value._id) { |
| 28 | // here you will receive messages |
| 29 | // console.log('This is the main thread ' + isMainThread) |
| 30 | this.runInAsyncScope(this._run.bind(this), this, fn, value) |
| 31 | } else if (value.parent) { |
| 32 | // save the port to communicate with the main thread |
| 33 | // this will be received once |
| 34 | this.parent = value.parent |
| 35 | } else if (value.kill) { |
| 36 | // here is time to kill this thread, just clearing the interval |
| 37 | clearInterval(this.interval) |
| 38 | this.emitDestroy() |
| 39 | } |
| 40 | }) |
| 41 | } |
| 42 | |
| 43 | _checkAlive () { |
| 44 | if ((Date.now() - this.lastTask) > this.maxInactiveTime) { |
| 45 | this.parent.postMessage({ kill: 1 }) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | _run (fn, value) { |
| 50 | try { |
| 51 | const res = fn(value.data) |
| 52 | this.parent.postMessage({ data: res, _id: value._id }) |
| 53 | this.lastTask = Date.now() |
| 54 | } catch (e) { |
| 55 | this.parent.postMessage({ error: e, _id: value._id }) |
| 56 | this.lastTask = Date.now() |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | module.exports.ThreadWorker = ThreadWorker |