1 import { EventEmitter
} from
'events'
2 import type { FixedThreadPoolOptions
, WorkerWithMessageChannel
} from
'./fixed'
3 import FixedThreadPool from
'./fixed'
5 class MyEmitter
extends EventEmitter
{}
7 export type DynamicThreadPoolOptions
= FixedThreadPoolOptions
10 * A thread pool with a min/max number of threads, is possible to execute tasks in sync or async mode as you prefer.
12 * This thread pool will create new workers when the other ones are busy, until the max number of threads,
13 * when the max number of threads is reached, an event will be emitted, if you want to listen this event use the emitter method.
15 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
18 export default class DynamicThreadPool
<
21 > extends FixedThreadPool
<Data
, Response
> {
22 public readonly emitter
: MyEmitter
25 * @param min Min number of threads that will be always active
26 * @param max Max number of threads that will be active
27 * @param filename A file path with implementation of `ThreadWorker` class, relative path is fine.
28 * @param opts An object with possible options for example `errorHandler`, `onlineHandler`. Default: `{ maxTasks: 1000 }`
31 public readonly min
: number,
32 public readonly max
: number,
33 public readonly filename
: string,
34 public readonly opts
: DynamicThreadPoolOptions
= { maxTasks
: 1000 }
36 super(min
, filename
, opts
)
38 this.emitter
= new MyEmitter()
41 protected _chooseWorker (): WorkerWithMessageChannel
{
42 let worker
: WorkerWithMessageChannel
43 for (const entry
of this.tasks
) {
51 // a worker is free, use it
54 if (this.workers
.length
=== this.max
) {
55 this.emitter
.emit('FullPool')
56 return super._chooseWorker()
58 // all workers are busy create a new worker
59 const worker
= this._newWorker()
60 worker
.port2
.on('message', (message
) => {
62 worker
.postMessage({ kill
: 1 })
71 module.exports
= DynamicThreadPool