Delete pullrequest.yml
[poolifier.git] / lib / dynamic.js
CommitLineData
a32e02ba 1'use strict'
2const FixedThreadPool = require('./fixed')
bf962cba 3const EventEmitter = require('events')
4class MyEmitter extends EventEmitter {}
a32e02ba 5
6/**
7 * A thread pool with a min/max number of threads , is possible to execute tasks in sync or async mode as you prefer. <br>
8 * This thread pool will create new workers when the other ones are busy, until the max number of threads,
bf962cba 9 * 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 10 * @author Alessandro Pio Ardizio
11 * @since 0.0.1
12 */
13class DynamicThreadPool extends FixedThreadPool {
14 /**
cf9aa6c3 15 *
16 * @param {Number} min Min number of threads that will be always active
17 * @param {Number} max Max number of threads that will be active
18 */
a32e02ba 19 constructor (min, max, filename, opts) {
20 super(min, filename, opts)
21 this.max = max
bf962cba 22 this.emitter = new MyEmitter()
23 }
24
a32e02ba 25 _chooseWorker () {
26 let worker
27 for (const entry of this.tasks) {
28 if (entry[1] === 0) {
29 worker = entry[0]
30 break
31 }
32 }
33
34 if (worker) {
35 // a worker is free, use it
36 return worker
37 } else {
38 if (this.workers.length === this.max) {
bf962cba 39 this.emitter.emit('FullPool')
34a572eb 40 return super._chooseWorker()
a32e02ba 41 }
a32e02ba 42 // all workers are busy create a new worker
43 const worker = this._newWorker()
cf9aa6c3 44 worker.port2.on('message', message => {
a32e02ba 45 if (message.kill) {
46 worker.postMessage({ kill: 1 })
47 worker.terminate()
bcf04003 48 // clean workers from data structures
cf9aa6c3 49 const workerIndex = this.workers.indexOf(worker)
50 this.workers.splice(workerIndex, 1)
bcf04003 51 this.tasks.delete(worker)
a32e02ba 52 }
53 })
54 return worker
55 }
56 }
57}
58
59module.exports = DynamicThreadPool