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