andywer / threads.js

🧡 Make web workers & worker threads as simple as a function call.
https://threads.js.org/
MIT License
3.07k stars 164 forks source link

`timeout` Option Documentation #494

Open aren55555 opened 1 month ago

aren55555 commented 1 month ago

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.

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 commented 1 month ago

I've created a public repo that reproduces the above: https://github.com/aren55555/threads-timeout-repro