e80276d976640c25a9fe194847289e1ba0d7db45
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 class DynamicThreadPool
<
19 // eslint-disable-next-line @typescript-eslint/no-explicit-any
21 // eslint-disable-next-line @typescript-eslint/no-explicit-any
23 > extends FixedThreadPool
<Data
, Response
> {
24 public readonly emitter
: MyEmitter
27 * @param min Min number of threads that will be always active
28 * @param max Max number of threads that will be active
29 * @param filename A file path with implementation of `ThreadWorker` class, relative path is fine.
30 * @param opts An object with possible options for example `errorHandler`, `onlineHandler`. Default: `{ maxTasks: 1000 }`
33 public readonly min
: number,
34 public readonly max
: number,
35 public readonly filename
: string,
36 public readonly opts
: DynamicThreadPoolOptions
= { maxTasks
: 1000 }
38 super(min
, filename
, opts
)
40 this.emitter
= new MyEmitter()
43 protected chooseWorker (): WorkerWithMessageChannel
{
44 let worker
: WorkerWithMessageChannel
| undefined
45 for (const entry
of this.tasks
) {
53 // a worker is free, use it
56 if (this.workers
.length
=== this.max
) {
57 this.emitter
.emit('FullPool')
58 return super.chooseWorker()
60 // all workers are busy create a new worker
61 const worker
= this.newWorker()
62 worker
.port2
?.on('message', (message
: { kill
?: number }) => {
64 worker
.postMessage({ kill
: 1 })
65 void worker
.terminate()
66 // clean workers from data structures
67 const workerIndex
= this.workers
.indexOf(worker
)
68 this.workers
.splice(workerIndex
, 1)
69 this.tasks
.delete(worker
)