X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fthread-worker.ts;h=4d4c1c3479f14970db523ff96d873f0b4cdac79f;hb=984dc9c8adc66d4ed982e76391db751dd685f0b2;hp=7a766a958ccbb41c9b29bbe76c04890eec61604d;hpb=bb4e9c3d36509745767905e4577d000087a23288;p=poolifier.git diff --git a/src/worker/thread-worker.ts b/src/worker/thread-worker.ts index 7a766a95..4d4c1c34 100644 --- a/src/worker/thread-worker.ts +++ b/src/worker/thread-worker.ts @@ -27,6 +27,10 @@ export class ThreadWorker< Data = unknown, Response = unknown > extends AbstractWorker { + /** + * Message port used to communicate with the main thread. + */ + private port!: MessagePort /** * Constructs a new poolifier thread worker. * @@ -42,22 +46,45 @@ export class ThreadWorker< 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 ( + !this.isMain && + 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 } }