1 import type { MessageValue
} from
'../../utility-types'
2 import type { PoolOptions
} from
'../abstract-pool'
3 import type { ThreadWorkerWithMessageChannel
} from
'./fixed'
4 import { FixedThreadPool
} from
'./fixed'
7 * A thread pool with a min/max number of threads, is possible to execute tasks in sync or async mode as you prefer.
9 * This thread pool will create new workers when the other ones are busy, until the max number of threads,
10 * when the max number of threads is reached, an event will be emitted, if you want to listen this event use the emitter method.
12 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
15 export class DynamicThreadPool
<
16 // eslint-disable-next-line @typescript-eslint/no-explicit-any
18 // eslint-disable-next-line @typescript-eslint/no-explicit-any
20 > extends FixedThreadPool
<Data
, Response
> {
22 * @param min Min number of threads that will be always active
23 * @param max Max number of threads that will be active
24 * @param filename A file path with implementation of `ThreadWorker` class, relative path is fine.
25 * @param opts An object with possible options for example `errorHandler`, `onlineHandler`. Default: `{ maxTasks: 1000 }`
29 public readonly max
: number,
31 opts
: PoolOptions
<ThreadWorkerWithMessageChannel
> = { maxTasks
: 1000 }
33 super(min
, filename
, opts
)
36 protected chooseWorker (): ThreadWorkerWithMessageChannel
{
37 let worker
: ThreadWorkerWithMessageChannel
| undefined
38 for (const entry
of this.tasks
) {
46 // a worker is free, use it
49 if (this.workers
.length
=== this.max
) {
50 this.emitter
.emit('FullPool')
51 return super.chooseWorker()
53 // all workers are busy create a new worker
54 const worker
= this.internalNewWorker()
55 worker
.port2
?.on('message', (message
: MessageValue
<Data
>) => {
57 this.sendToWorker(worker
, { kill
: 1 })
58 void this.destroyWorker(worker
)
59 // clean workers from data structures
60 const workerIndex
= this.workers
.indexOf(worker
)
61 this.workers
.splice(workerIndex
, 1)
62 this.tasks
.delete(worker
)