From 11f6df5f4d032f1d6c145ae29328f2587edf6bff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Goetz?= Date: Wed, 3 Jan 2024 18:23:50 +0100 Subject: [PATCH] Use a single global sharedBuffer --- src/index.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/index.ts b/src/index.ts index ebe24acd9..a0b8408ee 100644 --- a/src/index.ts +++ b/src/index.ts @@ -363,6 +363,9 @@ const _dirname = ? path.dirname(fileURLToPath(import.meta.url)) : /* istanbul ignore next */ __dirname +let sharedBuffer: SharedArrayBuffer | undefined +let sharedBufferView: Int32Array | undefined + export const generateGlobals = ( workerPath: string, globalShims: GlobalShim[], @@ -465,8 +468,8 @@ function startWorkerThread>( // We store a single Byte in the SharedArrayBuffer // for the notification, we can used a fixed size - const sharedBuffer = new SharedArrayBuffer(INT32_BYTES) - const sharedBufferView = new Int32Array(sharedBuffer, 0, 1) + sharedBuffer ??= new SharedArrayBuffer(INT32_BYTES) + sharedBufferView ??= new Int32Array(sharedBuffer, 0, 1) const useGlobals = finalGlobalShims.length > 0 @@ -503,9 +506,9 @@ function startWorkerThread>( const msg: MainToWorkerMessage> = { id, args } worker.postMessage(msg) - const status = Atomics.wait(sharedBufferView, 0, 0, timeout) + const status = Atomics.wait(sharedBufferView!, 0, 0, timeout) // Reset SharedArrayBuffer for next call - Atomics.store(sharedBufferView, 0, 0) + Atomics.store(sharedBufferView!, 0, 0) /* istanbul ignore if */ if (!['ok', 'not-equal'].includes(status)) {