6 } from
'node:worker_threads'
7 import type { MessageValue
} from
'../../utility-types.js'
8 import { AbstractPool
} from
'../abstract-pool.js'
9 import { type PoolOptions
, type PoolType
, PoolTypes
} from
'../pool.js'
10 import { type WorkerType
, WorkerTypes
} from
'../worker.js'
13 * Options for a poolifier thread pool.
15 export type ThreadPoolOptions
= PoolOptions
<Worker
>
18 * A thread pool with a fixed number of threads.
20 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
21 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
22 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
25 export class FixedThreadPool
<
28 > extends AbstractPool
<Worker
, Data
, Response
> {
30 * Constructs a new poolifier fixed thread pool.
32 * @param numberOfThreads - Number of threads for this pool.
33 * @param filePath - Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
34 * @param opts - Options for this fixed thread pool.
37 numberOfThreads
: number,
39 opts
: ThreadPoolOptions
= {},
40 maximumNumberOfThreads
?: number
42 super(numberOfThreads
, filePath
, opts
, maximumNumberOfThreads
)
46 protected isMain (): boolean {
51 protected sendToWorker (
52 workerNodeKey
: number,
53 message
: MessageValue
<Data
>,
54 transferList
?: TransferListItem
[]
56 this.workerNodes
[workerNodeKey
].messageChannel
?.port1
?.postMessage(
57 { ...message
, workerId
: this.getWorkerInfo(workerNodeKey
).id
},
63 protected sendStartupMessageToWorker (workerNodeKey
: number): void {
64 const workerNode
= this.workerNodes
[workerNodeKey
]
65 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
66 const port2
: MessagePort
= workerNode
.messageChannel
!.port2
67 workerNode
.worker
.postMessage(
70 workerId
: this.getWorkerInfo(workerNodeKey
).id
,
78 protected registerWorkerMessageListener
<Message
extends Data
| Response
>(
79 workerNodeKey
: number,
80 listener
: (message
: MessageValue
<Message
>) => void
82 this.workerNodes
[workerNodeKey
].messageChannel
?.port1
?.on(
89 protected registerOnceWorkerMessageListener
<Message
extends Data
| Response
>(
90 workerNodeKey
: number,
91 listener
: (message
: MessageValue
<Message
>) => void
93 this.workerNodes
[workerNodeKey
].messageChannel
?.port1
?.once(
100 protected deregisterWorkerMessageListener
<Message
extends Data
| Response
>(
101 workerNodeKey
: number,
102 listener
: (message
: MessageValue
<Message
>) => void
104 this.workerNodes
[workerNodeKey
].messageChannel
?.port1
?.off(
111 protected shallCreateDynamicWorker (): boolean {
116 protected checkAndEmitDynamicWorkerCreationEvents (): void {
121 protected get
type (): PoolType
{
122 return PoolTypes
.fixed
126 protected get
worker (): WorkerType
{
127 return WorkerTypes
.thread
131 protected get
busy (): boolean {
132 return this.internalBusy()