1 import type { JSONValue
, 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 Data
extends JSONValue
= JSONValue
,
17 Response
extends JSONValue
= JSONValue
18 > extends FixedThreadPool
<Data
, Response
> {
20 * @param min Min number of threads that will be always active
21 * @param max Max number of threads that will be active
22 * @param filename A file path with implementation of `ThreadWorker` class, relative path is fine.
23 * @param opts An object with possible options for example `errorHandler`, `onlineHandler`. Default: `{ maxTasks: 1000 }`
27 public readonly max
: number,
29 opts
: PoolOptions
<ThreadWorkerWithMessageChannel
> = { maxTasks
: 1000 }
31 super(min
, filename
, opts
)
34 protected chooseWorker (): ThreadWorkerWithMessageChannel
{
35 let worker
: ThreadWorkerWithMessageChannel
| undefined
36 for (const entry
of this.tasks
) {
44 // a worker is free, use it
47 if (this.workers
.length
=== this.max
) {
48 this.emitter
.emit('FullPool')
49 return super.chooseWorker()
51 // all workers are busy create a new worker
52 const worker
= this.internalNewWorker()
53 worker
.port2
?.on('message', (message
: MessageValue
<Data
>) => {
55 this.sendToWorker(worker
, { kill
: 1 })
56 void this.destroyWorker(worker
)
57 // clean workers from data structures
58 const workerIndex
= this.workers
.indexOf(worker
)
59 this.workers
.splice(workerIndex
, 1)
60 this.tasks
.delete(worker
)