8 } from
'node:worker_threads'
9 import type { MessageValue
} from
'../../utility-types'
10 import { AbstractPool
} from
'../abstract-pool'
11 import { type PoolOptions
, type PoolType
, PoolTypes
} from
'../pool'
12 import { type WorkerType
, WorkerTypes
} from
'../worker'
15 * Options for a poolifier thread pool.
17 export interface ThreadPoolOptions
extends PoolOptions
<Worker
> {
21 * @see https://nodejs.org/api/worker_threads.html#new-workerfilename-options
23 workerOptions
?: WorkerOptions
27 * A thread pool with a fixed number of threads.
29 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
30 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
31 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
34 export class FixedThreadPool
<
37 > extends AbstractPool
<Worker
, Data
, Response
> {
39 * Constructs a new poolifier fixed thread pool.
41 * @param numberOfThreads - Number of threads for this pool.
42 * @param filePath - Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
43 * @param opts - Options for this fixed thread pool.
46 numberOfThreads
: number,
48 protected readonly opts
: ThreadPoolOptions
= {}
50 super(numberOfThreads
, filePath
, opts
)
54 protected isMain (): boolean {
59 protected async destroyWorkerNode (workerNodeKey
: number): Promise
<void> {
60 const workerNode
= this.workerNodes
[workerNodeKey
]
61 const worker
= workerNode
.worker
62 this.sendToWorker(workerNodeKey
, { kill
: true, workerId
: worker
.threadId
})
63 workerNode
.closeChannel()
64 await worker
.terminate()
68 protected sendToWorker (
69 workerNodeKey
: number,
70 message
: MessageValue
<Data
>
73 this.getWorkerInfo(workerNodeKey
).messageChannel
as MessageChannel
74 ).port1
.postMessage(message
)
78 protected sendStartupMessageToWorker (workerNodeKey
: number): void {
79 const worker
= this.workerNodes
[workerNodeKey
].worker
80 const port2
: MessagePort
= (
81 this.getWorkerInfo(workerNodeKey
).messageChannel
as MessageChannel
86 workerId
: worker
.threadId
,
94 protected registerWorkerMessageListener
<Message
extends Data
| Response
>(
95 workerNodeKey
: number,
96 listener
: (message
: MessageValue
<Message
>) => void
99 this.getWorkerInfo(workerNodeKey
).messageChannel
as MessageChannel
100 ).port1
.on('message', listener
)
104 protected createWorker (): Worker
{
105 return new Worker(this.filePath
, {
107 ...this.opts
.workerOptions
112 protected get
type (): PoolType
{
113 return PoolTypes
.fixed
117 protected get
worker (): WorkerType
{
118 return WorkerTypes
.thread
122 protected get
minSize (): number {
123 return this.numberOfWorkers
127 protected get
maxSize (): number {
128 return this.numberOfWorkers
132 protected get
busy (): boolean {
133 return this.internalBusy()