4ed85c297e46836f867ac8e3bf3d9f3a60b42741
1 import type { MessagePort
} from
'worker_threads'
2 import { isMainThread
, parentPort
} from
'worker_threads'
3 import type { MessageValue
} from
'../utility-types'
4 import { EMPTY_OBJECT_LITERAL
} from
'../utils'
5 import { AbstractWorker
} from
'./abstract-worker'
6 import type { WorkerOptions
} from
'./worker-options'
9 * A thread worker used by a poolifier `ThreadPool`.
11 * When this worker is inactive for more than the given `maxInactiveTime`,
12 * it will send a termination request to its main thread.
14 * If you use a `DynamicThreadPool` the extra workers that were created will be terminated,
15 * but the minimum number of workers will be guaranteed.
17 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data.
18 * @typeParam Response - Type of response the worker sends back to the main thread. This can only be serializable data.
19 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
22 export class ThreadWorker
<
25 > extends AbstractWorker
<MessagePort
, Data
, Response
> {
27 * Constructs a new poolifier thread worker.
29 * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
30 * @param opts - Options for the worker.
33 fn
: (data
: Data
) => Response
,
34 opts
: WorkerOptions
= EMPTY_OBJECT_LITERAL
36 super('worker-thread-pool:poolifier', isMainThread
, fn
, parentPort
, opts
)
40 protected sendToMainWorker (message
: MessageValue
<Response
>): void {
41 this.getMainWorker().postMessage(message
)