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