X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fthread-worker.ts;h=e208eb4063656dccf1ed25a8c12463c6de1302e5;hb=29d8b961b1907797d251871a97092973d342c63c;hp=7a766a958ccbb41c9b29bbe76c04890eec61604d;hpb=f59e102739e13698f278f1d9d58ab26ed8150442;p=poolifier.git diff --git a/src/worker/thread-worker.ts b/src/worker/thread-worker.ts index 7a766a95..e208eb40 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,10 @@ 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,30 +38,50 @@ 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, + taskFunctions, opts ) - if (!this.isMain) { - this.sendToMainWorker({ workerId: this.id, started: true }) + } + + /** @inheritDoc */ + protected handleReadyMessage (message: MessageValue): void { + if ( + message.workerId === this.id && + message.ready != null && + message.port != null + ) { + this.port = message.port + this.port.on('message', this.messageListener.bind(this)) + this.sendToMainWorker({ ready: true, workerId: this.id }) } } + /** @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 { - console.log('sending message to main worker(thread)', message) - this.getMainWorker().postMessage(message) + this.port.postMessage(message) + } + + /** @inheritDoc */ + protected handleError (e: Error | string): string { + return e as string } }