Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node:worker_threads exits too early #22934

Closed
bartlomieju opened this issue Mar 14, 2024 · 0 comments · Fixed by #22944
Closed

node:worker_threads exits too early #22934

bartlomieju opened this issue Mar 14, 2024 · 0 comments · Fixed by #22944
Assignees
Labels
bug Something isn't working correctly node API Related to various "node:*" modules APIs node compat

Comments

@bartlomieju
Copy link
Member

Version: Deno 1.41.3

This bug was introduced in #22647.

Consider following script:

// worker.mjs
import { isMainThread, Worker } from "node:worker_threads";

if (isMainThread) {
  // This re-loads the current file inside a Worker instance.
  const w = new Worker(import.meta.filename);
} else {
  console.log("Inside Worker!");
  console.log(isMainThread); // Prints 'false'.
}
$ deno run -A worker.mjs
Inside Worker!
false

$ node worker.mjs
Inside Worker!
false

Consider this script:

// worker.mjs
import { isMainThread, parentPort, Worker } from "node:worker_threads";

if (isMainThread) {
  // This re-loads the current file inside a Worker instance.
  const w = new Worker(import.meta.filename);
} else {
  console.log("Inside Worker!");
  console.log(isMainThread); // Prints 'false'.
  parentPort.on("message", () => console.log("Got message from main thread");
}
$ deno run -A worker.mjs
Inside Worker!
false
# exits

$ node worker.mjs
Inside Worker!
false
# waits indefinitely

And this one:

// worker.mjs
import { isMainThread, parentPort, Worker } from "node:worker_threads";

function onMessageOneshot() {
  console.log("Got message from main thread!");
  parentPort.off("message", onMessageOneshot);
}

if (isMainThread) {
  // This re-loads the current file inside a Worker instance.
  const w = new Worker(import.meta.filename);

  setTimeout(() => {
    w.postMessage("Hello! I am from the main thread.");
  }, 1000);
} else {
  console.log("Inside Worker!");
  console.log(isMainThread); // Prints 'false'.
  parentPort.on("message", onMessageOneshot);
}
$ deno run -A worker.mjs
Inside Worker!
false
# exits

$ node worker.mjs
Inside Worker!
false
# waits 1s
Got message from main thread!
# exits

We need to fix condition for unrefing the op waiting for message inside a worker. We should only unref the op if there are no active message listeners.

Ref #22911

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working correctly node API Related to various "node:*" modules APIs node compat
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants