super('worker-thread-pool:pioardi')
this.opts = opts || {}
this.maxInactiveTime = this.opts.maxInactiveTime || (1000 * 60)
+ this.async = !!this.opts.async
this.lastTask = Date.now()
if (!fn) throw new Error('Fn parameter is mandatory')
// keep the worker active
if (value && value.data && value._id) {
// here you will receive messages
// console.log('This is the main thread ' + isMainThread)
- this.runInAsyncScope(this._run.bind(this), this, fn, value)
+ if (this.async) {
+ this.runInAsyncScope(this._runAsync.bind(this), this, fn, value)
+ } else {
+ this.runInAsyncScope(this._run.bind(this), this, fn, value)
+ }
} else if (value.parent) {
// save the port to communicate with the main thread
// this will be received once
this.lastTask = Date.now()
}
}
+
+ _runAsync(fn, value) {
+ fn(value.data).then(res => {
+ this.parent.postMessage({ data: res, _id: value._id })
+ this.lastTask = Date.now()
+ }).catch(e => {
+ this.parent.postMessage({ error: e, _id: value._id })
+ this.lastTask = Date.now()
+ })
+ }
}
module.exports.ThreadWorker = ThreadWorker
{
- "name": "node-thread-pool",
+ "name": "poolifier",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
const emptyPool = new FixedThreadPool(1, './tests/workers/emptyWorker.js')
const echoPool = new FixedThreadPool(1, './tests/workers/echoWorker.js')
const errorPool = new FixedThreadPool(1, './tests/workers/errorWorker.js', { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
+const asyncPool = new FixedThreadPool(1, './tests/workers/asyncWorker.js')
describe('Fixed thread pool test suite ', () => {
it('Choose worker round robin test', async () => {
expect(inError.message).toBeTruthy()
})
+ it('Verify that async function is working properly', async () => {
+ const data = { f: 10 }
+ const startTime = new Date().getTime()
+ const result = await asyncPool.execute(data)
+ const usedTime = new Date().getTime() - startTime
+ expect(result).toBeTruthy()
+ expect(result.f).toBe(data.f)
+ expect(usedTime).toBeGreaterThan(2000)
+ })
+
it('Shutdown test', async () => {
let closedThreads = 0
pool.workers.forEach(w => {
--- /dev/null
+'use strict'
+const { ThreadWorker } = require('../../lib/workers')
+
+async function sleep (data) {
+ return new Promise((resolve, reject) => {
+ setTimeout(() => resolve(data), 2000)
+ })
+}
+
+module.exports = new ThreadWorker(sleep, { maxInactiveTime: 500, async: true })
\ No newline at end of file