6 } from
'node:worker_threads'
8 import type { MessageValue
} from
'../utility-types.js'
9 import { AbstractWorker
} from
'./abstract-worker.js'
10 import type { TaskFunction
, TaskFunctions
} from
'./task-functions.js'
11 import type { WorkerOptions
} from
'./worker-options.js'
14 * A thread worker used by a poolifier `ThreadPool`.
16 * When this worker is inactive for more than the given `maxInactiveTime`,
17 * it will send a termination request to its main thread.
19 * If you use a `DynamicThreadPool` the extra workers that were created will be terminated,
20 * but the minimum number of workers will be guaranteed.
22 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
23 * @typeParam Response - Type of response the worker sends back to the main thread. This can only be structured-cloneable data.
24 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
27 export class ThreadWorker
<
30 > extends AbstractWorker
<MessagePort
, Data
, Response
> {
32 * Message port used to communicate with the main worker.
34 private port
?: MessagePort
37 * Constructs a new poolifier thread worker.
39 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
40 * @param opts - Options for the worker.
43 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
44 opts
: WorkerOptions
= {}
46 super(isMainThread
, parentPort
, taskFunctions
, opts
)
50 protected handleReadyMessage (message
: MessageValue
<Data
>): void {
52 message
.workerId
=== this.id
&&
53 message
.ready
=== false &&
57 this.port
= message
.port
58 this.port
.on('message', this.messageListener
.bind(this))
59 this.sendToMainWorker({
61 taskFunctionsProperties
: this.listTaskFunctionsProperties()
64 this.sendToMainWorker({
66 taskFunctionsProperties
: this.listTaskFunctionsProperties()
73 protected handleKillMessage (message
: MessageValue
<Data
>): void {
74 super.handleKillMessage(message
)
80 protected get
id (): number {
85 protected readonly sendToMainWorker
= (
86 message
: MessageValue
<Response
>
88 this.port
?.postMessage({
91 } satisfies MessageValue
<Response
>)
98 protected handleError (error
: Error | string): string {
99 return error
as string