6 } from
'node:worker_threads'
7 import type { MessageValue
} from
'../../utility-types'
8 import { AbstractPool
} from
'../abstract-pool'
9 import { type PoolOptions
, type PoolType
, PoolTypes
} from
'../pool'
10 import { type WorkerType
, WorkerTypes
} from
'../worker'
13 * Options for a poolifier thread pool.
15 export interface ThreadPoolOptions
extends PoolOptions
<Worker
> {
19 * @see https://nodejs.org/api/worker_threads.html#new-workerfilename-options
21 workerOptions
?: WorkerOptions
25 * A thread pool with a fixed number of threads.
27 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
28 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
29 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
32 export class FixedThreadPool
<
35 > extends AbstractPool
<Worker
, Data
, Response
> {
37 * Constructs a new poolifier fixed thread pool.
39 * @param numberOfThreads - Number of threads for this pool.
40 * @param filePath - Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
41 * @param opts - Options for this fixed thread pool.
44 numberOfThreads
: number,
46 protected readonly opts
: ThreadPoolOptions
= {}
48 super(numberOfThreads
, filePath
, opts
)
52 protected isMain (): boolean {
57 protected async destroyWorker (worker
: Worker
): Promise
<void> {
58 this.sendToWorker(worker
, { kill
: true, workerId
: worker
.threadId
})
59 await worker
.terminate()
63 protected sendToWorker (worker
: Worker
, message
: MessageValue
<Data
>): void {
64 worker
.postMessage(message
)
68 protected createWorker (): Worker
{
69 return new Worker(this.filePath
, {
71 ...this.opts
.workerOptions
76 protected get
type (): PoolType
{
77 return PoolTypes
.fixed
81 protected get
worker (): WorkerType
{
82 return WorkerTypes
.thread
86 protected get
minSize (): number {
87 return this.numberOfWorkers
91 protected get
maxSize (): number {
92 return this.numberOfWorkers
96 protected get
busy (): boolean {
97 return this.internalBusy()