|
| 1 | +import * as assert from 'node:assert/strict'; |
| 2 | +import { test } from 'node:test'; |
| 3 | +import { resolve } from 'node:path'; |
| 4 | +import Piscina from '..'; |
| 5 | + |
| 6 | +const READY_SIGNAL = 0; |
| 7 | +const TASK_SIGNAL = 1; |
| 8 | + |
| 9 | +test('a queued task prefers a ready worker over a still-pending one', async () => { |
| 10 | + const gates = new Int32Array( |
| 11 | + new SharedArrayBuffer(2 * Int32Array.BYTES_PER_ELEMENT) |
| 12 | + ); |
| 13 | + |
| 14 | + Atomics.store(gates, READY_SIGNAL, 1); |
| 15 | + |
| 16 | + const pool = new Piscina({ |
| 17 | + filename: resolve(__dirname, 'fixtures/wait-until-released.js'), |
| 18 | + minThreads: 1, |
| 19 | + maxThreads: 2, |
| 20 | + concurrentTasksPerWorker: 1, |
| 21 | + workerData: gates.buffer |
| 22 | + }); |
| 23 | + |
| 24 | + // One ready, idle worker. |
| 25 | + const warmThreadId = await pool.run({}); |
| 26 | + |
| 27 | + // Keep the next worker from becoming ready. |
| 28 | + Atomics.store(gates, READY_SIGNAL, 0); |
| 29 | + |
| 30 | + // Occupy the ready worker, then queue a task behind it. A second worker |
| 31 | + // spawns but stays pending. |
| 32 | + const held = pool.run({ hold: true }); |
| 33 | + const queued = pool.run({}); |
| 34 | + |
| 35 | + // Free the ready worker while the second is still pending: the queued task |
| 36 | + // should land on the ready worker. |
| 37 | + Atomics.store(gates, TASK_SIGNAL, 1); |
| 38 | + Atomics.notify(gates, TASK_SIGNAL, Infinity); |
| 39 | + |
| 40 | + const heldThreadId = await held; |
| 41 | + |
| 42 | + // Let the second worker finish so the pool can shut down (and the queued task |
| 43 | + // resolves even if it was wrongly routed there). |
| 44 | + Atomics.store(gates, READY_SIGNAL, 1); |
| 45 | + Atomics.notify(gates, READY_SIGNAL, Infinity); |
| 46 | + |
| 47 | + const queuedThreadId = await queued; |
| 48 | + |
| 49 | + assert.strictEqual(heldThreadId, warmThreadId); |
| 50 | + assert.strictEqual( |
| 51 | + queuedThreadId, |
| 52 | + warmThreadId, |
| 53 | + 'queued task should go to the ready worker, not the still-pending one' |
| 54 | + ); |
| 55 | + |
| 56 | + await pool.destroy(); |
| 57 | +}); |
0 commit comments