diff --git a/examples/napi/__test__/worker-thread.spec.ts b/examples/napi/__test__/worker-thread.spec.ts index 74423849..11778421 100644 --- a/examples/napi/__test__/worker-thread.spec.ts +++ b/examples/napi/__test__/worker-thread.spec.ts @@ -13,6 +13,7 @@ t('should be able to require in worker thread', async (t) => { Array.from({ length: 100 }).map(() => { const w = new Worker(join(__dirname, 'worker.js')) return new Promise((resolve, reject) => { + w.postMessage({ type: 'require' }) w.on('message', (msg) => { t.is(msg, Animal.withKind(Kind.Cat).whoami() + DEFAULT_COST) resolve() @@ -28,3 +29,42 @@ t('should be able to require in worker thread', async (t) => { }), ) }) + +t('custom GC works on worker_threads', async (t) => { + await Promise.all( + Array.from({ length: 50 }).map(() => + Promise.all([ + new Promise((resolve, reject) => { + const w = new Worker(join(__dirname, 'worker.js')) + w.postMessage({ + type: 'async:buffer', + }) + w.on('message', (msg) => { + t.is(msg, 'done') + resolve(w) + }) + w.on('error', (err) => { + reject(err) + }) + }).then((w) => { + return w.terminate() + }), + new Promise((resolve, reject) => { + const w = new Worker(join(__dirname, 'worker.js')) + w.postMessage({ + type: 'async:arraybuffer', + }) + w.on('message', (msg) => { + t.is(msg, 'done') + resolve(w) + }) + w.on('error', (err) => { + reject(err) + }) + }).then((w) => { + return w.terminate() + }), + ]), + ), + ) +}) diff --git a/examples/napi/__test__/worker.js b/examples/napi/__test__/worker.js index fee47128..392041a5 100644 --- a/examples/napi/__test__/worker.js +++ b/examples/napi/__test__/worker.js @@ -2,6 +2,41 @@ const { parentPort } = require('worker_threads') const native = require('../index') -parentPort.postMessage( - native.Animal.withKind(native.Kind.Cat).whoami() + native.DEFAULT_COST, -) +parentPort.on('message', ({ type }) => { + switch (type) { + case 'require': + parentPort.postMessage( + native.Animal.withKind(native.Kind.Cat).whoami() + native.DEFAULT_COST, + ) + break + case 'async:buffer': + Promise.all( + Array.from({ length: 100 }).map(() => + native.bufferPassThrough(Buffer.from([1, 2, 3])), + ), + ) + .then(() => { + parentPort.postMessage('done') + }) + .catch((e) => { + throw e + }) + break + case 'async:arraybuffer': + Promise.all( + Array.from({ length: 100 }).map(() => + native.arrayBufferPassThrough(Uint8Array.from([1, 2, 3])), + ), + ) + .then(() => { + parentPort.postMessage('done') + }) + .catch((e) => { + throw e + }) + + break + default: + throw new TypeError(`Unknown message type: ${type}`) + } +})