perf: use a single array to store pool workers and their related data
[poolifier.git] / src / pools / thread / dynamic.ts
CommitLineData
bdaf31cd 1import type { PoolOptions } from '../pool'
7c0ba920 2import { PoolType } from '../pool-internal'
c97c7edb 3import type { ThreadWorkerWithMessageChannel } from './fixed'
325f50bc 4import { FixedThreadPool } from './fixed'
f045358d 5
4ade5f1f 6/**
729c563d 7 * A thread pool with a dynamic number of threads, but a guaranteed minimum number of threads.
4ade5f1f 8 *
729c563d
S
9 * This thread pool creates new threads when the others are busy, up to the maximum number of threads.
10 * When the maximum number of threads is reached, an event is emitted. If you want to listen to this event, use the pool's `emitter`.
11 *
38e795c1
JB
12 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
13 * @typeParam Response - Type of response of execution. This can only be serializable data.
4ade5f1f
S
14 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
15 * @since 0.0.1
16 */
60fbd6d6 17export class DynamicThreadPool<
deb85c12
JB
18 Data = unknown,
19 Response = unknown
4ade5f1f 20> extends FixedThreadPool<Data, Response> {
4ade5f1f 21 /**
729c563d
S
22 * Constructs a new poolifier dynamic thread pool.
23 *
38e795c1
JB
24 * @param min - Minimum number of threads which are always active.
25 * @param max - Maximum number of threads that can be created by this pool.
26 * @param filePath - Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
27 * @param opts - Options for this dynamic thread pool.
4ade5f1f
S
28 */
29 public constructor (
c97c7edb 30 min: number,
a8884ffd 31 protected readonly max: number,
31b90205 32 filePath: string,
1927ee67 33 opts: PoolOptions<ThreadWorkerWithMessageChannel> = {}
4ade5f1f 34 ) {
31b90205 35 super(min, filePath, opts)
4ade5f1f
S
36 }
37
38e795c1 38 /** {@inheritDoc} */
7c0ba920
JB
39 public get type (): PoolType {
40 return PoolType.DYNAMIC
41 }
42
38e795c1 43 /** {@inheritDoc} */
7c0ba920 44 public get busy (): boolean {
e65c6cd9 45 return this.workers.length === this.max
4ade5f1f
S
46 }
47}