Skip to content

Commit d8bda36

Browse files
authored
Fix error when runing multiple times in worker (#13)
1 parent ae5291c commit d8bda36

File tree

2 files changed

+18
-8
lines changed

2 files changed

+18
-8
lines changed

index.js

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ const IS_WORKER_MARK = 'is-make-synchronous-worker';
1010
const IS_WORKER = workerData?.[IS_WORKER_MARK];
1111

1212
function setupWorker(function_) {
13-
parentPort.on('message', async ({arguments_, workerPort, semaphore}) => {
13+
const {workerPort} = workerData;
14+
parentPort.on('message', async ({arguments_, semaphore}) => {
1415
try {
1516
workerPort.postMessage({result: await function_(...arguments_)});
1617
} catch (error) {
@@ -27,6 +28,10 @@ function makeSynchronous(function_) {
2728

2829
function createWorker() {
2930
if (!cache) {
31+
const {port1: mainThreadPort, port2: workerPort} = new MessageChannel();
32+
mainThreadPort.unref();
33+
workerPort.unref();
34+
3035
const code = `
3136
import setupWorker from ${JSON.stringify(import.meta.url)};
3237
@@ -36,26 +41,24 @@ function makeSynchronous(function_) {
3641
const worker = new Worker(code, {
3742
eval: true,
3843
workerData: {
44+
workerPort,
3945
[IS_WORKER_MARK]: true,
4046
},
47+
transferList: [workerPort],
4148
});
4249
worker.unref();
4350

44-
const {port1: mainThreadPort, port2: workerPort} = new MessageChannel();
45-
mainThreadPort.unref();
46-
workerPort.unref();
47-
48-
cache = {worker, mainThreadPort, workerPort};
51+
cache = {worker, mainThreadPort};
4952
}
5053

5154
return cache;
5255
}
5356

5457
return (...arguments_) => {
55-
const {worker, mainThreadPort, workerPort} = createWorker();
58+
const {worker, mainThreadPort} = createWorker();
5659
const semaphore = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
5760

58-
worker.postMessage({arguments_, semaphore, workerPort}, [workerPort]);
61+
worker.postMessage({arguments_, semaphore});
5962
Atomics.wait(semaphore, 0, 0);
6063

6164
const {error, result} = receiveMessageOnPort(mainThreadPort).message;

test.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,11 @@ for (const {type, makeSynchronous} of [
6161
},
6262
);
6363
});
64+
65+
test(`[${type}] Run multiple times`, t => {
66+
const identity = makeSynchronous(value => Promise.resolve(value));
67+
for (let index = 0; index < 2; index++) {
68+
t.is(identity(index), index);
69+
}
70+
});
6471
}

0 commit comments

Comments
 (0)