Update README.MD
[poolifier.git] / lib / fixed.js
index 63e62bade18bf12d7779186516e30445e5e1eaaa..645528283d80807cbc5374b5184c64b0f4c83c9e 100644 (file)
@@ -2,8 +2,6 @@
 const {
   Worker, isMainThread, MessageChannel, SHARE_ENV
 } = require('worker_threads')
-const path = require('path')
-const { generateID } = require('./util')
 
 function empty () {}
 /**
@@ -16,17 +14,18 @@ class FixedThreadPool {
   /**
     *
     * @param {Number} numThreads  Num of threads for this worker pool
-    * @param {string} a file path with implementation of @see ThreadWorker class
+    * @param {string} a file path with implementation of @see ThreadWorker class, relative path is fine
     * @param {Object} an object with possible options for example errorHandler, onlineHandler.
   */
-  constructor (numThreads, filename, opts) {
+  constructor (numThreads, filePath, opts) {
     if (!isMainThread) throw new Error('Cannot start a thread pool from a worker thread !!!')
-    if (!filename) throw new Error('Please specify a file with a worker implementation')
+    if (!filePath) throw new Error('Please specify a file with a worker implementation')
     this.numThreads = numThreads
     this.workers = []
     this.nextWorker = 0
     this.opts = opts || { maxTasks: 1000 }
-    this.filename = filename
+    this.filePath = filePath
+    this._id = 0
     // threadId as key and an integer value
     this.tasks = new Map()
     for (let i = 1; i <= numThreads; i++) {
@@ -38,7 +37,6 @@ class FixedThreadPool {
     for (const worker of this.workers) {
       worker.terminate()
     }
-    this.emitDestroy()
   }
 
   /**
@@ -50,10 +48,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()
-    data._id = id
+    const id = ++this._id
     const res = this._execute(worker, id)
-    worker.postMessage(data)
+    worker.postMessage({ data: data, _id: id })
     return res
   }
 
@@ -81,7 +78,7 @@ class FixedThreadPool {
   }
 
   _newWorker () {
-    const worker = new Worker(path.resolve(this.filename), { env: SHARE_ENV })
+    const worker = new Worker(this.filePath, { env: SHARE_ENV })
     worker.on('error', this.opts.errorHandler || empty)
     worker.on('online', this.opts.onlineHandler || empty)
     // TODO handle properly when a thread exit