fix: fix default task function handling with multiple task functions
[poolifier.git] / src / worker / thread-worker.ts
CommitLineData
fc3e6586
JB
1import type { MessagePort } from 'node:worker_threads'
2import { isMainThread, parentPort } from 'node:worker_threads'
a86b6df1
JB
3import type {
4 MessageValue,
5 TaskFunctions,
6 WorkerFunction
7} from '../utility-types'
c97c7edb 8import { AbstractWorker } from './abstract-worker'
325f50bc 9import type { WorkerOptions } from './worker-options'
a32e02ba 10
a32e02ba 11/**
729c563d 12 * A thread worker used by a poolifier `ThreadPool`.
4ade5f1f 13 *
729c563d
S
14 * When this worker is inactive for more than the given `maxInactiveTime`,
15 * it will send a termination request to its main thread.
16 *
17 * If you use a `DynamicThreadPool` the extra workers that were created will be terminated,
18 * but the minimum number of workers will be guaranteed.
19 *
38e795c1
JB
20 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data.
21 * @typeParam Response - Type of response the worker sends back to the main thread. This can only be serializable data.
4ade5f1f 22 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
a32e02ba 23 * @since 0.0.1
24 */
d3c8a1a8 25export class ThreadWorker<
deb85c12
JB
26 Data = unknown,
27 Response = unknown
d3c8a1a8 28> extends AbstractWorker<MessagePort, Data, Response> {
729c563d
S
29 /**
30 * Constructs a new poolifier thread worker.
31 *
82888165 32 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
38e795c1 33 * @param opts - Options for the worker.
729c563d 34 */
d4aeae5a 35 public constructor (
82888165
JB
36 taskFunctions:
37 | WorkerFunction<Data, Response>
38 | TaskFunctions<Data, Response>,
d4aeae5a
JB
39 opts: WorkerOptions = {}
40 ) {
82888165
JB
41 super(
42 'worker-thread-pool:poolifier',
43 isMainThread,
44 taskFunctions,
45 parentPort,
46 opts
47 )
106744f7 48 }
7784f548 49
afc003b2 50 /** @inheritDoc */
c97c7edb
S
51 protected sendToMainWorker (message: MessageValue<Response>): void {
52 this.getMainWorker().postMessage(message)
7784f548 53 }
a32e02ba 54}