a32e02ba |
1 | 'use strict' |
2 | const { |
3 | isMainThread, parentPort |
4 | } = require('worker_threads') |
50811da2 |
5 | const { AsyncResource } = require('async_hooks') |
a32e02ba |
6 | |
a32e02ba |
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 | */ |
50811da2 |
14 | class ThreadWorker extends AsyncResource { |
506c2a14 |
15 | constructor (fn, opts) { |
50811da2 |
16 | super('worker-thread-pool:pioardi') |
506c2a14 |
17 | this.opts = opts || {} |
18 | this.maxInactiveTime = this.opts.maxInactiveTime || (1000 * 60) |
a32e02ba |
19 | this.lastTask = Date.now() |
20 | if (!fn) throw new Error('Fn parameter is mandatory') |
21 | // keep the worker active |
22 | if (!isMainThread) { |
506c2a14 |
23 | this.interval = setInterval(this._checkAlive.bind(this), this.maxInactiveTime / 2) |
a32e02ba |
24 | this._checkAlive.bind(this)() |
25 | } |
26 | parentPort.on('message', (value) => { |
506c2a14 |
27 | if (value && value.data && value._id) { |
a32e02ba |
28 | // here you will receive messages |
29 | // console.log('This is the main thread ' + isMainThread) |
8950a941 |
30 | this.runInAsyncScope(this._run.bind(this), this, fn, value) |
a32e02ba |
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) |
34a572eb |
38 | this.emitDestroy() |
a32e02ba |
39 | } |
40 | }) |
41 | } |
42 | |
43 | _checkAlive () { |
506c2a14 |
44 | if ((Date.now() - this.lastTask) > this.maxInactiveTime) { |
a32e02ba |
45 | this.parent.postMessage({ kill: 1 }) |
46 | } |
47 | } |
106744f7 |
48 | |
49 | _run (fn, value) { |
50 | try { |
8950a941 |
51 | const res = fn(value.data) |
106744f7 |
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 | } |
a32e02ba |
59 | } |
60 | |
61 | module.exports.ThreadWorker = ThreadWorker |