X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;ds=sidebyside;f=lib%2Ffixed.js;h=676947725bed0bb65fe72fe949be8652b08f39c5;hb=a06c72d6a04f3e5e7f9abb48bdf24926e1d81029;hp=833ae7b6f1f048c8ff0a92e7eb42a1bdacd36b78;hpb=506c2a140687bf8b1a1313a8d7aeb9e3f0f142a7;p=poolifier.git
diff --git a/lib/fixed.js b/lib/fixed.js
index 833ae7b6..67694772 100644
--- a/lib/fixed.js
+++ b/lib/fixed.js
@@ -2,9 +2,9 @@
const {
Worker, isMainThread, MessageChannel, SHARE_ENV
} = require('worker_threads')
-const { generateID } = require('./util')
function empty () {}
+const _void = {}
/**
* A thread pool with a static number of threads , is possible to execute tasks in sync or async mode as you prefer.
* This pool will select the worker thread in a round robin fashion.
@@ -26,6 +26,7 @@ class FixedThreadPool {
this.nextWorker = 0
this.opts = opts || { maxTasks: 1000 }
this.filePath = filePath
+ this._id = 0
// threadId as key and an integer value
this.tasks = new Map()
for (let i = 1; i <= numThreads; i++) {
@@ -33,9 +34,9 @@ class FixedThreadPool {
}
}
- destroy () {
+ async destroy () {
for (const worker of this.workers) {
- worker.terminate()
+ await worker.terminate()
}
}
@@ -48,9 +49,9 @@ class FixedThreadPool {
// configure worker to handle message with the specified task
const worker = this._chooseWorker()
this.tasks.set(worker, this.tasks.get(worker) + 1)
- const id = generateID()
+ const id = ++this._id
const res = this._execute(worker, id)
- worker.postMessage({ data: data, _id: id })
+ worker.postMessage({ data: data || _void, _id: id })
return res
}
@@ -60,7 +61,8 @@ class FixedThreadPool {
if (message._id === id) {
worker.port2.removeListener('message', listener)
this.tasks.set(worker, this.tasks.get(worker) - 1)
- resolve(message.data)
+ if (message.error) reject(message.error)
+ else resolve(message.data)
}
}
worker.port2.on('message', listener)