1 import { EventEmitter
} from
'events'
4 FixedThreadPoolOptions
,
5 WorkerWithMessageChannel
8 class MyEmitter
extends EventEmitter
{}
10 export type DynamicThreadPoolOptions
= FixedThreadPoolOptions
13 * A thread pool with a min/max number of threads, is possible to execute tasks in sync or async mode as you prefer.
15 * This thread pool will create new workers when the other ones are busy, until the max number of threads,
16 * when the max number of threads is reached, an event will be emitted, if you want to listen this event use the emitter method.
18 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
21 /* eslint-disable @typescript-eslint/no-explicit-any */
22 export class DynamicThreadPool
<
25 > extends FixedThreadPool
<Data
, Response
> {
26 /* eslint-enable @typescript-eslint/no-explicit-any */
27 public readonly emitter
: MyEmitter
30 * @param min Min number of threads that will be always active
31 * @param max Max number of threads that will be active
32 * @param filename A file path with implementation of `ThreadWorker` class, relative path is fine.
33 * @param opts An object with possible options for example `errorHandler`, `onlineHandler`. Default: `{ maxTasks: 1000 }`
36 public readonly min
: number,
37 public readonly max
: number,
38 public readonly filename
: string,
39 public readonly opts
: DynamicThreadPoolOptions
= { maxTasks
: 1000 }
41 super(min
, filename
, opts
)
43 this.emitter
= new MyEmitter()
46 protected chooseWorker (): WorkerWithMessageChannel
{
47 let worker
: WorkerWithMessageChannel
| undefined
48 for (const entry
of this.tasks
) {
56 // a worker is free, use it
59 if (this.workers
.length
=== this.max
) {
60 this.emitter
.emit('FullPool')
61 return super.chooseWorker()
63 // all workers are busy create a new worker
64 const worker
= this.newWorker()
65 worker
.port2
?.on('message', (message
: { kill
?: number }) => {
67 worker
.postMessage({ kill
: 1 })
68 void worker
.terminate()
69 // clean workers from data structures
70 const workerIndex
= this.workers
.indexOf(worker
)
71 this.workers
.splice(workerIndex
, 1)
72 this.tasks
.delete(worker
)