idle-timeout.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import Piscina from '..';
  2. import { test } from 'tap';
  3. import { resolve } from 'path';
  4. import { promisify } from 'util';
  5. const delay = promisify(setTimeout);
  6. test('idle timeout will let go of threads early', async ({ equal }) => {
  7. const pool = new Piscina({
  8. filename: resolve(__dirname, 'fixtures/wait-for-others.ts'),
  9. idleTimeout: 500,
  10. minThreads: 1,
  11. maxThreads: 2
  12. });
  13. equal(pool.threads.length, 1);
  14. const buffer = new Int32Array(new SharedArrayBuffer(4));
  15. const firstTasks = [
  16. pool.runTask([buffer, 2]),
  17. pool.runTask([buffer, 2])
  18. ];
  19. equal(pool.threads.length, 2);
  20. const earlyThreadIds = await Promise.all(firstTasks);
  21. equal(pool.threads.length, 2);
  22. await delay(2000);
  23. equal(pool.threads.length, 1);
  24. const secondTasks = [
  25. pool.runTask([buffer, 4]),
  26. pool.runTask([buffer, 4])
  27. ];
  28. equal(pool.threads.length, 2);
  29. const lateThreadIds = await Promise.all(secondTasks);
  30. // One thread should have been idle in between and exited, one should have
  31. // been reused.
  32. equal(earlyThreadIds.length, 2);
  33. equal(lateThreadIds.length, 2);
  34. equal(new Set([...earlyThreadIds, ...lateThreadIds]).size, 3);
  35. });