6 } from
'node:worker_threads'
7 import type { MessageValue
} from
'../utility-types.js'
8 import { AbstractWorker
} from
'./abstract-worker.js'
9 import type { WorkerOptions
} from
'./worker-options.js'
10 import type { TaskFunction
, TaskFunctions
} from
'./task-functions.js'
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 worker.
33 private port
?: MessagePort
36 * Constructs a new poolifier thread worker.
38 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
39 * @param opts - Options for the worker.
42 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
43 opts
: WorkerOptions
= {}
45 super(isMainThread
, parentPort
as MessagePort
, taskFunctions
, opts
)
49 protected handleReadyMessage (message
: MessageValue
<Data
>): void {
51 message
.workerId
=== this.id
&&
52 message
.ready
=== false &&
56 this.port
= message
.port
57 this.port
.on('message', this.messageListener
.bind(this))
58 this.sendToMainWorker({
60 taskFunctionNames
: this.listTaskFunctionNames()
63 this.sendToMainWorker({
65 taskFunctionNames
: this.listTaskFunctionNames()
72 protected handleKillMessage (message
: MessageValue
<Data
>): void {
73 super.handleKillMessage(message
)
79 protected get
id (): number {
84 protected readonly sendToMainWorker
= (
85 message
: MessageValue
<Response
>
87 this.port
?.postMessage({ ...message
, workerId
: this.id
})
94 protected handleError (error
: Error | string): string {
95 return error
as string