Working implementation with a very good benchmark based on num of threads
[poolifier.git] / worker.js
1 'use strict'
2 const {
3 isMainThread, parentPort
4 } = require('worker_threads')
5
6 /**
7 * An example worker that will be always alive, you just need to extend this class if you want a static pool.
8 * @author Alessandro Pio Ardizio
9 * @since 0.0.1
10 */
11 class ThreadWorker {
12 constructor (fn) {
13 if (!fn) throw new Error('Fn parameter is mandatory')
14 // keep the worker active
15 if (!isMainThread) {
16 this.interval =
17 setInterval(() => {
18 }, 10000)
19 }
20 parentPort.on('message', (value) => {
21 if (value.parent) {
22 // save the port to communicate with the main thread
23 this.parent = value.parent
24 } else if (value && value._id) {
25 // console.log('This is the main thread ' + isMainThread)
26 this.parent.postMessage({ data: fn(value), _id: value._id })
27 }
28 })
29 }
30 }
31
32 module.exports = ThreadWorker