Fix tests run on node 10.x and add test assertion
[poolifier.git] / lib / dynamic.js
CommitLineData
a32e02ba 1'use strict'
2const FixedThreadPool = require('./fixed')
bf962cba 3const { randomWorker } = require('./util')
4const EventEmitter = require('events')
5class MyEmitter extends EventEmitter {}
a32e02ba 6
7/**
8 * A thread pool with a min/max number of threads , is possible to execute tasks in sync or async mode as you prefer. <br>
9 * This thread pool will create new workers when the other ones are busy, until the max number of threads,
bf962cba 10 * when the max number of threads is reached, an event will be emitted , if you want to listen this event use the emitter method.
a32e02ba 11 * @author Alessandro Pio Ardizio
12 * @since 0.0.1
13 */
14class DynamicThreadPool extends FixedThreadPool {
15 /**
16 *
17 * @param {Number} min Min number of threads that will be always active
18 * @param {Number} max Max number of threads that will be active
19 * @param {Object} an object with possible options for example maxConcurrency
20 */
21 constructor (min, max, filename, opts) {
22 super(min, filename, opts)
23 this.max = max
bf962cba 24 this.emitter = new MyEmitter()
25 }
26
a32e02ba 27 _chooseWorker () {
28 let worker
29 for (const entry of this.tasks) {
30 if (entry[1] === 0) {
31 worker = entry[0]
32 break
33 }
34 }
35
36 if (worker) {
37 // a worker is free, use it
38 return worker
39 } else {
40 if (this.workers.length === this.max) {
bf962cba 41 this.emitter.emit('FullPool')
42 return randomWorker(this.tasks)
a32e02ba 43 }
a32e02ba 44 // all workers are busy create a new worker
45 const worker = this._newWorker()
46 worker.port2.on('message', (message) => {
47 if (message.kill) {
48 worker.postMessage({ kill: 1 })
49 worker.terminate()
50 }
51 })
52 return worker
53 }
54 }
55}
56
57module.exports = DynamicThreadPool