a8658f03a797ed649cbd583a14ed5d924949a235
6 } from
'node:worker_threads'
7 import type { MessageValue
} from
'../utility-types'
8 import { AbstractWorker
} from
'./abstract-worker'
9 import type { WorkerOptions
} from
'./worker-options'
10 import type { TaskFunctions
, WorkerFunction
} from
'./worker-functions'
13 * A thread worker used by a poolifier `ThreadPool`.
15 * When this worker is inactive for more than the given `maxInactiveTime`,
16 * it will send a termination request to its main thread.
18 * If you use a `DynamicThreadPool` the extra workers that were created will be terminated,
19 * but the minimum number of workers will be guaranteed.
21 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
22 * @typeParam Response - Type of response the worker sends back to the main thread. This can only be structured-cloneable data.
23 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
26 export class ThreadWorker
<
29 > extends AbstractWorker
<MessagePort
, Data
, Response
> {
31 * Message port used to communicate with the main thread.
33 private port
!: MessagePort
35 * Constructs a new poolifier thread worker.
37 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
38 * @param opts - Options for the worker.
42 | WorkerFunction
<Data
, Response
>
43 | TaskFunctions
<Data
, Response
>,
44 opts
: WorkerOptions
= {}
47 'worker-thread-pool:poolifier',
49 parentPort
as MessagePort
,
56 protected handleReadyMessage (message
: MessageValue
<Data
>): void {
58 message
.workerId
=== this.id
&&
59 message
.ready
!= null &&
63 this.port
= message
.port
64 this.port
.on('message', this.messageListener
.bind(this))
65 this.sendToMainWorker({ ready
: true, workerId
: this.id
})
71 protected get
id (): number {
76 protected sendToMainWorker (message
: MessageValue
<Response
>): void {
77 this.port
.postMessage(message
)
81 protected handleError (e
: Error | string): string {