X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fthread-worker.ts;h=bc143a1f914b7e7dba14b395ac456be40c59ed80;hb=de868be6cc9bcfb6d341ffb14e6407c24a1a0e17;hp=2b3df58361eb28a9d0ccc2f694208bb0e4426c02;hpb=e8a4c3ea4d5123ff7c158d139ca142144ccc1117;p=poolifier.git diff --git a/src/worker/thread-worker.ts b/src/worker/thread-worker.ts index 2b3df583..bc143a1f 100644 --- a/src/worker/thread-worker.ts +++ b/src/worker/thread-worker.ts @@ -7,7 +7,7 @@ import { import type { MessageValue } from '../utility-types' import { AbstractWorker } from './abstract-worker' import type { WorkerOptions } from './worker-options' -import type { TaskFunctions, WorkerFunction } from './worker-functions' +import type { TaskFunction, TaskFunctions } from './task-functions' /** * A thread worker used by a poolifier `ThreadPool`. @@ -27,6 +27,11 @@ export class ThreadWorker< Data = unknown, Response = unknown > extends AbstractWorker { + /** + * Message port used to communicate with the main worker. + */ + private port?: MessagePort + /** * Constructs a new poolifier thread worker. * @@ -34,26 +39,59 @@ export class ThreadWorker< * @param opts - Options for the worker. */ public constructor ( - taskFunctions: - | WorkerFunction - | TaskFunctions, + taskFunctions: TaskFunction | TaskFunctions, opts: WorkerOptions = {} ) { - super( - 'worker-thread-pool:poolifier', - isMainThread, - taskFunctions, - parentPort as MessagePort, - opts - ) + super(isMainThread, parentPort as MessagePort, taskFunctions, opts) + } + + /** @inheritDoc */ + protected handleReadyMessage (message: MessageValue): void { + if ( + message.workerId === this.id && + message.ready === false && + message.port != null + ) { + try { + this.port = message.port + this.port.on('message', this.messageListener.bind(this)) + this.sendToMainWorker({ + ready: true, + taskFunctionNames: this.listTaskFunctionNames() + }) + } catch { + this.sendToMainWorker({ + ready: false, + taskFunctionNames: this.listTaskFunctionNames() + }) + } + } + } + + /** @inheritDoc */ + protected handleKillMessage (message: MessageValue): void { + super.handleKillMessage(message) + this.port?.unref() + this.port?.close() } + /** @inheritDoc */ protected get id (): number { return threadId } /** @inheritDoc */ - protected sendToMainWorker (message: MessageValue): void { - this.getMainWorker().postMessage(message) + protected readonly sendToMainWorker = ( + message: MessageValue + ): void => { + this.port?.postMessage({ ...message, workerId: this.id }) + } + + /** + * @inheritDoc + * @override + */ + protected handleError (error: Error | string): string { + return error as string } }