threads.js icon indicating copy to clipboard operation
threads.js copied to clipboard

`timeout` Option Documentation

Open aren55555 opened this issue 4 months ago • 1 comments

Hello there 👋🏽

First of all thanks for the library and your contribution to open source. I had a question regarding the timeout option. I could not find any documentation on this topic, however if I have missed it please do point it out.

  • I'm using Node.js, version v20.17.0
  • I've called the spawn method with a timeout option set to 1000 milliseconds (or 1 second).
  • Inside the actual "work" method sleeper, the execution was paused for 30000 milliseconds (or 30 seconds).

Here's the code:

main.ts

import { spawn, Worker } from "threads"

const main = async () => {
  console.log('START MAIN', { now : new Date() });

  const worker = await spawn(new Worker("./worker"), {
    timeout: 1000, // 1 second
  });

  // const workerResult = await worker.dies();
  const workerResult = await worker.sleeper();
  console.log('MAIN got result from WORKER', { workerResult });

  console.log('END MAIN', { now : new Date() });
}

main();

worker.ts

import { expose } from "threads/worker"

const sleep = (ms: number) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}

expose({
  sleeper: async () => {
    console.log('WORKER START', { now : new Date() });
    await sleep(30000); // 30 seconds
    console.log('WORKER END', { now : new Date() });
    return 'value from worker';
  },
  dies: async () => {
    console.log('WORKER exits', { now : new Date() });
    process.exit(0);
  },
});

I'd expect that the timeout should kick in here... the promise awaited in main.ts has taken longer than the timeout, so it seems like the promise should reject?

output:

START MAIN { now: 2024-09-30T23:07:50.151Z }
WORKER START { now: 2024-09-30T23:07:50.273Z }
WORKER END { now: 2024-09-30T23:08:20.275Z }
MAIN got result from WORKER { workerResult: 'value from worker' }
END MAIN { now: 2024-09-30T23:08:20.280Z }

Similarly (and related), if instead I call the worker and it exits (or dies) by swapping the commented out line in main.ts:

const workerResult = await worker.dies();
// const workerResult = await worker.sleeper();
START MAIN { now: 2024-09-30T23:12:47.611Z }
WORKER exits { now: 2024-09-30T23:12:47.725Z }

The promise in main.ts never rejects or resolves, despite having set the timeout.

So I'm wondering, how should I expect this timeout to behave? What effect does it have? Does this work?

aren55555 avatar Sep 30 '24 23:09 aren55555