X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=lib%2Fworkers.js;h=8641ed9e871deafce80c0adafd5b9531443ec209;hb=e7752b742dd463f8a525d1de7b8dbb0b73963cec;hp=e6d43c698de5b85cd0ec61baa479c32f1f8b7cc9;hpb=a32e02baa991ae01b5d677e3fd34821965daab1e;p=poolifier.git
diff --git a/lib/workers.js b/lib/workers.js
index e6d43c69..8641ed9e 100644
--- a/lib/workers.js
+++ b/lib/workers.js
@@ -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.
* When this worker is inactive for more than 1 minute, it will send this info to the main thread,
@@ -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