Update README.MD
[poolifier.git] / lib / workers.js
CommitLineData
a32e02ba 1'use strict'
2const {
3 isMainThread, parentPort
4} = require('worker_threads')
50811da2 5const { 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 14class 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)
506c2a14 30 const res = this.runInAsyncScope(fn, null, value.data)
50811da2 31 this.parent.postMessage({ data: res, _id: value._id })
a32e02ba 32 this.lastTask = Date.now()
33 } else if (value.parent) {
34 // save the port to communicate with the main thread
35 // this will be received once
36 this.parent = value.parent
37 } else if (value.kill) {
38 // here is time to kill this thread, just clearing the interval
39 clearInterval(this.interval)
40 }
41 })
42 }
43
44 _checkAlive () {
506c2a14 45 if ((Date.now() - this.lastTask) > this.maxInactiveTime) {
a32e02ba 46 this.parent.postMessage({ kill: 1 })
47 }
48 }
49}
50
51module.exports.ThreadWorker = ThreadWorker