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