Update README.MD
[poolifier.git] / lib / workers.js
index e6d43c698de5b85cd0ec61baa479c32f1f8b7cc9..8641ed9e871deafce80c0adafd5b9531443ec209 100644 (file)
@@ -2,34 +2,9 @@
 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>
@@ -37,8 +12,9 @@ class ThreadWorker {
  * @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
@@ -50,7 +26,8 @@ class DynamicWorker {
       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
@@ -71,4 +48,3 @@ class DynamicWorker {
 }
 
 module.exports.ThreadWorker = ThreadWorker
-module.exports.DynamicWorker = DynamicWorker