1 import { isMainThread
, parentPort
} from
'worker_threads'
2 import type { MessageValue
} from
'../utility-types'
3 import { AbstractWorker
} from
'./abstract-worker'
4 import type { WorkerOptions
} from
'./worker-options'
7 * An example worker that will be always alive, you just need to **extend** this class if you want a static pool.
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.
12 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
15 // eslint-disable-next-line @typescript-eslint/no-explicit-any
16 export class ThreadWorker
<Data
= any, Response
= any> extends AbstractWorker
<
21 protected parent?: MessagePort
23 public constructor (fn
: (data
: Data
) => Response
, opts
: WorkerOptions
= {}) {
24 super('worker-thread-pool:pioardi', isMainThread
, fn
, opts
)
26 parentPort
?.on('message', (value
: MessageValue
<Data
>) => {
27 if (value
?.data
&& value
.id
) {
28 // here you will receive messages
29 // console.log('This is the main worker ' + isMain)
31 this.runInAsyncScope(this.runAsync
.bind(this), this, fn
, value
)
33 this.runInAsyncScope(this.run
.bind(this), this, fn
, value
)
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
) {
40 // here is time to kill this worker, just clearing the interval
41 if (this.interval
) clearInterval(this.interval
)
47 protected getMainWorker (): MessagePort
{
49 throw new Error('Parent was not set')
54 protected sendToMainWorker (message
: MessageValue
<Response
>): void {
55 this.getMainWorker().postMessage(message
)