7 } from
'node:worker_threads'
8 import type { Draft
, MessageValue
} from
'../../utility-types'
9 import { AbstractPool
} from
'../abstract-pool'
19 * Options for a poolifier thread pool.
21 export interface ThreadPoolOptions
extends PoolOptions
<Worker
> {
25 * @see https://nodejs.org/api/worker_threads.html#new-workerfilename-options
27 workerOptions
?: WorkerOptions
31 * A thread worker with message channels for communication between main thread and thread worker.
33 export type ThreadWorkerWithMessageChannel
= Worker
& Draft
<MessageChannel
>
36 * A thread pool with a fixed number of threads.
38 * It is possible to perform tasks in sync or asynchronous mode as you prefer.
40 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
41 * @typeParam Response - Type of execution response. This can only be serializable data.
42 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
45 export class FixedThreadPool
<
48 > extends AbstractPool
<ThreadWorkerWithMessageChannel
, Data
, Response
> {
50 * Constructs a new poolifier fixed thread pool.
52 * @param numberOfThreads - Number of threads for this pool.
53 * @param filePath - Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
54 * @param opts - Options for this fixed thread pool.
57 numberOfThreads
: number,
59 protected readonly opts
: ThreadPoolOptions
= {}
61 super(numberOfThreads
, filePath
, opts
)
65 protected isMain (): boolean {
70 protected async destroyWorker (
71 worker
: ThreadWorkerWithMessageChannel
73 this.sendToWorker(worker
, { kill
: 1 })
74 await worker
.terminate()
78 protected sendToWorker (
79 worker
: ThreadWorkerWithMessageChannel
,
80 message
: MessageValue
<Data
>
82 worker
.postMessage(message
)
86 protected registerWorkerMessageListener
<Message
extends Data
| Response
>(
87 worker
: ThreadWorkerWithMessageChannel
,
88 listener
: (message
: MessageValue
<Message
>) => void
90 worker
.port2
?.on('message', listener
)
94 protected createWorker (): ThreadWorkerWithMessageChannel
{
95 return new Worker(this.filePath
, {
97 ...this.opts
.workerOptions
102 protected afterWorkerSetup (worker
: ThreadWorkerWithMessageChannel
): void {
103 const { port1
, port2
} = new MessageChannel()
104 worker
.postMessage({ parent: port1
}, [port1
])
107 // Listen to worker messages.
108 this.registerWorkerMessageListener(worker
, super.workerListener())
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()