Skip to content

Commit

Permalink
Use a single global sharedBuffer
Browse files Browse the repository at this point in the history
  • Loading branch information
onigoetz committed Jan 3, 2024
1 parent 9311e43 commit 11f6df5
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[],
Expand Down Expand Up @@ -465,8 +468,8 @@ function startWorkerThread<R, T extends AnyAsyncFn<R>>(

// 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

Expand Down Expand Up @@ -503,9 +506,9 @@ function startWorkerThread<R, T extends AnyAsyncFn<R>>(
const msg: MainToWorkerMessage<Parameters<T>> = { 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)) {
Expand Down

0 comments on commit 11f6df5

Please sign in to comment.