a32e02ba |
1 | 'use strict' |
2 | const FixedThreadPool = require('./fixed') |
3 | |
4 | /** |
5 | * A thread pool with a min/max number of threads , is possible to execute tasks in sync or async mode as you prefer. <br> |
6 | * This thread pool will create new workers when the other ones are busy, until the max number of threads, |
7 | * when the max number of threads is reached, an exception will be thrown. |
8 | * This pool will select the worker thread in a round robin fashion. <br> |
9 | * @author Alessandro Pio Ardizio |
10 | * @since 0.0.1 |
11 | */ |
12 | class DynamicThreadPool extends FixedThreadPool { |
13 | /** |
14 | * |
15 | * @param {Number} min Min number of threads that will be always active |
16 | * @param {Number} max Max number of threads that will be active |
17 | * @param {Object} an object with possible options for example maxConcurrency |
18 | */ |
19 | constructor (min, max, filename, opts) { |
20 | super(min, filename, opts) |
21 | this.max = max |
22 | } |
23 | |
24 | _chooseWorker () { |
25 | let worker |
26 | for (const entry of this.tasks) { |
27 | if (entry[1] === 0) { |
28 | worker = entry[0] |
29 | break |
30 | } |
31 | } |
32 | |
33 | if (worker) { |
34 | // a worker is free, use it |
35 | return worker |
36 | } else { |
37 | if (this.workers.length === this.max) { |
38 | throw new Error('Max number of threads reached !!!') |
39 | } |
40 | // console.log('new thread is coming') |
41 | // all workers are busy create a new worker |
42 | const worker = this._newWorker() |
43 | worker.port2.on('message', (message) => { |
44 | if (message.kill) { |
45 | worker.postMessage({ kill: 1 }) |
46 | worker.terminate() |
47 | } |
48 | }) |
49 | return worker |
50 | } |
51 | } |
52 | } |
53 | |
54 | module.exports = DynamicThreadPool |