6 } from
'node:worker_threads'
7 import type { MessageValue
} from
'../../utility-types'
8 import { AbstractPool
} from
'../abstract-pool'
18 * Options for a poolifier thread pool.
20 export interface ThreadPoolOptions
extends PoolOptions
<Worker
> {
24 * @see https://nodejs.org/api/worker_threads.html#new-workerfilename-options
26 workerOptions
?: WorkerOptions
30 * A thread pool with a fixed number of threads.
32 * It is possible to perform tasks in sync or asynchronous mode as you prefer.
34 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
35 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
36 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
39 export class FixedThreadPool
<
42 > extends AbstractPool
<Worker
, Data
, Response
> {
44 * Constructs a new poolifier fixed thread pool.
46 * @param numberOfThreads - Number of threads for this pool.
47 * @param filePath - Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
48 * @param opts - Options for this fixed thread pool.
51 numberOfThreads
: number,
53 protected readonly opts
: ThreadPoolOptions
= {}
55 super(numberOfThreads
, filePath
, opts
)
59 protected isMain (): boolean {
64 protected async destroyWorker (worker
: Worker
): Promise
<void> {
65 this.sendToWorker(worker
, { kill
: 1 })
66 await worker
.terminate()
70 protected sendToWorker (worker
: Worker
, message
: MessageValue
<Data
>): void {
71 worker
.postMessage(message
)
75 protected createWorker (): Worker
{
76 return new Worker(this.filePath
, {
78 ...this.opts
.workerOptions
83 protected get
type (): PoolType
{
84 return PoolTypes
.fixed
88 protected get
worker (): WorkerType
{
89 return WorkerTypes
.thread
93 protected get
minSize (): number {
94 return this.numberOfWorkers
98 protected get
maxSize (): number {
99 return this.numberOfWorkers
103 protected get
busy (): boolean {
104 return this.internalBusy()