feat: support multiple functions per worker
[poolifier.git] / src / worker / thread-worker.ts
1 import type { MessagePort } from 'node:worker_threads'
2 import { isMainThread, parentPort } from 'node:worker_threads'
3 import type {
4 MessageValue,
5 TaskFunctions,
6 WorkerFunction
7 } from '../utility-types'
8 import { AbstractWorker } from './abstract-worker'
9 import type { WorkerOptions } from './worker-options'
10
11 /**
12 * A thread worker used by a poolifier `ThreadPool`.
13 *
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 *
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.
22 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
23 * @since 0.0.1
24 */
25 export class ThreadWorker<
26 Data = unknown,
27 Response = unknown
28 > extends AbstractWorker<MessagePort, Data, Response> {
29 /**
30 * Constructs a new poolifier thread worker.
31 *
32 * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
33 * @param opts - Options for the worker.
34 */
35 public constructor (
36 fn: WorkerFunction<Data, Response> | TaskFunctions<Data, Response>,
37 opts: WorkerOptions = {}
38 ) {
39 super('worker-thread-pool:poolifier', isMainThread, fn, parentPort, opts)
40 }
41
42 /** @inheritDoc */
43 protected sendToMainWorker (message: MessageValue<Response>): void {
44 this.getMainWorker().postMessage(message)
45 }
46 }