Skip to content

Commit 9fac5fb

Browse files
committed
Add tests for worker threads.
#13
1 parent eac2a4d commit 9fac5fb

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

test/functional-tests.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@ Promise.withResolvers = Promise.withResolvers ?? function() {
99
};
1010

1111
await import('./tests/basic-tests.js');
12+
await import('./tests/worker-threads-tests.js');
1213
//await import('./tests/reference-count-tests.js');

test/tests/worker-threads-tests.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { Worker, isMainThread, parentPort } from 'node:worker_threads';
2+
import { fileURLToPath } from 'node:url';
3+
import { describe, it } from 'node:test';
4+
import { strict as assert } from 'node:assert';
5+
import { create } from '../../index.js';
6+
7+
if (isMainThread) {
8+
describe('worker threads tests', () => {
9+
it('can request adapter in multiple worker threads simultaneously', async () => {
10+
const numWorkers = 4;
11+
const workers = [];
12+
13+
// Initialize in main thread to ensure no conflict with workers
14+
const gpu = create([]);
15+
const adapter = await gpu.requestAdapter();
16+
assert.ok(adapter, 'Main thread got adapter');
17+
18+
for (let i = 0; i < numWorkers; i++) {
19+
workers.push(new Promise((resolve, reject) => {
20+
const worker = new Worker(fileURLToPath(import.meta.url));
21+
worker.on('message', (msg) => {
22+
if (msg === 'success') resolve();
23+
else reject(new Error(`Worker failed: ${msg}`));
24+
});
25+
worker.on('error', reject);
26+
worker.on('exit', (code) => {
27+
if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
28+
});
29+
}));
30+
}
31+
32+
await Promise.all(workers);
33+
});
34+
});
35+
} else {
36+
// Worker code
37+
async function run() {
38+
const { create } = await import('../../index.js');
39+
const gpu = create([]);
40+
const adapter = await gpu.requestAdapter();
41+
if (adapter) {
42+
parentPort.postMessage('success');
43+
} else {
44+
parentPort.postMessage('failure');
45+
}
46+
}
47+
run().catch(err => {
48+
parentPort.postMessage(err.message || String(err));
49+
process.exit(1);
50+
});
51+
}

0 commit comments

Comments
 (0)