X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fthread-worker.ts;h=ede0b3b5602f6335e2fc0c3409a719fd5edbf5b6;hb=71cad0b00456d2f7cf0987604062674ff19b44c4;hp=a8658f03a797ed649cbd583a14ed5d924949a235;hpb=85aeb3f356d749b96361e74cf17d403a697e3dd7;p=poolifier.git diff --git a/src/worker/thread-worker.ts b/src/worker/thread-worker.ts index a8658f03..ede0b3b5 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`. @@ -28,7 +28,7 @@ export class ThreadWorker< Response = unknown > extends AbstractWorker { /** - * Message port used to communicate with the main thread. + * Message port used to communicate with the main worker. */ private port!: MessagePort /** @@ -38,9 +38,7 @@ export class ThreadWorker< * @param opts - Options for the worker. */ public constructor ( - taskFunctions: - | WorkerFunction - | TaskFunctions, + taskFunctions: TaskFunction | TaskFunctions, opts: WorkerOptions = {} ) { super( @@ -56,17 +54,34 @@ export class ThreadWorker< protected handleReadyMessage (message: MessageValue): void { if ( message.workerId === this.id && - message.ready != null && + message.ready === false && message.port != null ) { - if (!this.isMain) { + try { this.port = message.port this.port.on('message', this.messageListener.bind(this)) - this.sendToMainWorker({ ready: true, workerId: this.id }) + this.sendToMainWorker({ + ready: true, + taskFunctionNames: this.listTaskFunctionNames(), + workerId: this.id + }) + } catch { + this.sendToMainWorker({ + ready: false, + taskFunctionNames: this.listTaskFunctionNames(), + 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