Commit | Line | Data |
---|---|---|
fa699c42 | 1 | import { isMainThread, parentPort } from 'worker_threads' |
325f50bc | 2 | import type { MessageValue } from '../utility-types' |
c97c7edb | 3 | import { AbstractWorker } from './abstract-worker' |
325f50bc | 4 | import type { WorkerOptions } from './worker-options' |
a32e02ba | 5 | |
a32e02ba | 6 | /** |
4ade5f1f S |
7 | * An example worker that will be always alive, you just need to **extend** this class if you want a static pool. |
8 | * | |
9 | * When this worker is inactive for more than 1 minute, it will send this info to the main thread, | |
10 | * if you are using DynamicThreadPool, the workers created after will be killed, the min num of thread will be guaranteed. | |
11 | * | |
12 | * @author [Alessandro Pio Ardizio](https://github.com/pioardi) | |
a32e02ba | 13 | * @since 0.0.1 |
14 | */ | |
777b7824 | 15 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
c97c7edb S |
16 | export class ThreadWorker<Data = any, Response = any> extends AbstractWorker< |
17 | MessagePort, | |
18 | Data, | |
19 | Response | |
20 | > { | |
ee99693b | 21 | protected parent?: MessagePort |
4ade5f1f | 22 | |
c97c7edb S |
23 | public constructor (fn: (data: Data) => Response, opts: WorkerOptions = {}) { |
24 | super('worker-thread-pool:pioardi', isMainThread, fn, opts) | |
4ade5f1f | 25 | |
325f50bc S |
26 | parentPort?.on('message', (value: MessageValue<Data>) => { |
27 | if (value?.data && value.id) { | |
28 | // here you will receive messages | |
c97c7edb | 29 | // console.log('This is the main worker ' + isMain) |
325f50bc S |
30 | if (this.async) { |
31 | this.runInAsyncScope(this.runAsync.bind(this), this, fn, value) | |
32 | } else { | |
33 | this.runInAsyncScope(this.run.bind(this), this, fn, value) | |
7784f548 | 34 | } |
325f50bc S |
35 | } else if (value.parent) { |
36 | // save the port to communicate with the main thread | |
37 | // this will be received once | |
38 | this.parent = value.parent | |
39 | } else if (value.kill) { | |
c97c7edb | 40 | // here is time to kill this worker, just clearing the interval |
325f50bc S |
41 | if (this.interval) clearInterval(this.interval) |
42 | this.emitDestroy() | |
a32e02ba | 43 | } |
325f50bc | 44 | }) |
a32e02ba | 45 | } |
46 | ||
c97c7edb S |
47 | protected getMainWorker (): MessagePort { |
48 | if (!this.parent) { | |
49 | throw new Error('Parent was not set') | |
106744f7 | 50 | } |
c97c7edb | 51 | return this.parent |
106744f7 | 52 | } |
7784f548 | 53 | |
c97c7edb S |
54 | protected sendToMainWorker (message: MessageValue<Response>): void { |
55 | this.getMainWorker().postMessage(message) | |
7784f548 | 56 | } |
a32e02ba | 57 | } |