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