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