Skip to content

Commit

Permalink
Pass useBuffer with workerData
Browse files Browse the repository at this point in the history
  • Loading branch information
onigoetz committed Dec 29, 2023
1 parent 555c4a0 commit e04fa68
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
16 changes: 8 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,10 @@ function startWorkerThread<R, T extends AnyAsyncFn<R>>(
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(
Expand All @@ -507,16 +511,12 @@ function startWorkerThread<R, T extends AnyAsyncFn<R>>(
: 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<T>): R => {
Expand All @@ -525,7 +525,7 @@ function startWorkerThread<R, T extends AnyAsyncFn<R>>(
// Reset SharedArrayBuffer
Atomics.store(sharedBufferView, 0, 0)

const msg: MainToWorkerMessage<Parameters<T>> = { id, useBuffer, args }
const msg: MainToWorkerMessage<Parameters<T>> = { id, args }
worker.postMessage(msg)

const status = Atomics.wait(sharedBufferView, 0, 0, timeout)
Expand Down Expand Up @@ -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<Parameters<T>>) => {
({ id, args }: MainToWorkerMessage<Parameters<T>>) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
;(async () => {
const sharedBufferView = new Int32Array(sharedBuffer)
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ export type ValueOf<T> = T[keyof T]

export interface MainToWorkerMessage<T extends unknown[]> {
id: number
useBuffer: boolean
args: T
}

export interface WorkerData {
sharedBuffer: SharedArrayBuffer
useBuffer: boolean
workerPort: MessagePort
}

Expand Down

0 comments on commit e04fa68

Please sign in to comment.