feat: support multiple functions per worker
[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 *
38e795c1
JB
32 * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
33 * @param opts - Options for the worker.
729c563d 34 */
d4aeae5a 35 public constructor (
a86b6df1 36 fn: WorkerFunction<Data, Response> | TaskFunctions<Data, Response>,
d4aeae5a
JB
37 opts: WorkerOptions = {}
38 ) {
e088a00c 39 super('worker-thread-pool:poolifier', isMainThread, fn, parentPort, opts)
106744f7 40 }
7784f548 41
afc003b2 42 /** @inheritDoc */
c97c7edb
S
43 protected sendToMainWorker (message: MessageValue<Response>): void {
44 this.getMainWorker().postMessage(message)
7784f548 45 }
a32e02ba 46}