From e04fa68d54a4036fb6949459be6a1be7cead3a1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Goetz?= Date: Fri, 29 Dec 2023 11:28:23 +0100 Subject: [PATCH] Pass useBuffer with workerData --- src/index.ts | 16 ++++++++-------- src/types.ts | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/index.ts b/src/index.ts index 45f5fe5f7..8a9388fe4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -490,6 +490,10 @@ function startWorkerThread>( const sharedBuffer = new SharedArrayBuffer(bufferSize) const sharedBufferView = new Int32Array(sharedBuffer) + // SharedArrayBuffer is faster to pass a response back, but has a limited size. + // We use this feature only if we can automatically resize the SharedArrayBuffer. + const useBuffer = sharedBuffer.growable + const worker = new Worker( (jsUseEsm && useGlobals) || (tsUseEsm && finalTsRunner === TsRunner.TsNode) ? dataUrl( @@ -507,16 +511,12 @@ function startWorkerThread>( : workerPathUrl, { eval: useEval, - workerData: { workerPort, sharedBuffer }, + workerData: { workerPort, sharedBuffer, useBuffer }, transferList: [workerPort, ...transferList], execArgv: finalExecArgv, }, ) - // SharedArrayBuffer is faster to pass a response back, but has a limited size. - // We use this feature only if we can automatically resize the SharedArrayBuffer. - const useBuffer = sharedBuffer.growable - let nextID = 0 const syncFn = (...args: Parameters): R => { @@ -525,7 +525,7 @@ function startWorkerThread>( // Reset SharedArrayBuffer Atomics.store(sharedBufferView, 0, 0) - const msg: MainToWorkerMessage> = { id, useBuffer, args } + const msg: MainToWorkerMessage> = { id, args } worker.postMessage(msg) const status = Atomics.wait(sharedBufferView, 0, 0, timeout) @@ -574,11 +574,11 @@ export function runAsWorker< return } - const { sharedBuffer, workerPort } = workerData as WorkerData + const { sharedBuffer, useBuffer, workerPort } = workerData as WorkerData parentPort!.on( 'message', - ({ id, useBuffer, args }: MainToWorkerMessage>) => { + ({ id, args }: MainToWorkerMessage>) => { // eslint-disable-next-line @typescript-eslint/no-floating-promises ;(async () => { const sharedBufferView = new Int32Array(sharedBuffer) diff --git a/src/types.ts b/src/types.ts index 1d38390d2..b330cd1bc 100644 --- a/src/types.ts +++ b/src/types.ts @@ -23,12 +23,12 @@ export type ValueOf = T[keyof T] export interface MainToWorkerMessage { id: number - useBuffer: boolean args: T } export interface WorkerData { sharedBuffer: SharedArrayBuffer + useBuffer: boolean workerPort: MessagePort }