const {
isMainThread, parentPort
} = require('worker_threads')
+const { AsyncResource } = require('async_hooks')
const maxInactiveTime = 1000 * 60
-/**
- * An example worker that will be always alive, you just need to extend this class if you want a static pool.
- * @author Alessandro Pio Ardizio
- * @since 0.0.1
- */
-class ThreadWorker {
- constructor (fn) {
- if (!fn) throw new Error('Fn parameter is mandatory')
- // keep the worker active
- if (!isMainThread) {
- this.interval =
- setInterval(() => {
- }, 10000)
- }
- parentPort.on('message', (value) => {
- if (value.parent) {
- // save the port to communicate with the main thread
- this.parent = value.parent
- } else if (value && value._id) {
- // console.log('This is the main thread ' + isMainThread)
- this.parent.postMessage({ data: fn(value), _id: value._id })
- }
- })
- }
-}
-
/**
* An example worker that will be always alive, you just need to extend this class if you want a static pool.<br>
* When this worker is inactive for more than 1 minute, it will send this info to the main thread,<br>
* @author Alessandro Pio Ardizio
* @since 0.0.1
*/
-class DynamicWorker {
+class ThreadWorker extends AsyncResource {
constructor (fn) {
+ super('worker-thread-pool:pioardi')
this.lastTask = Date.now()
if (!fn) throw new Error('Fn parameter is mandatory')
// keep the worker active
if (value && value._id) {
// here you will receive messages
// console.log('This is the main thread ' + isMainThread)
- this.parent.postMessage({ data: fn(value), _id: value._id })
+ const res = this.runInAsyncScope(fn, null, value)
+ this.parent.postMessage({ data: res, _id: value._id })
this.lastTask = Date.now()
} else if (value.parent) {
// save the port to communicate with the main thread
}
module.exports.ThreadWorker = ThreadWorker
-module.exports.DynamicWorker = DynamicWorker