Skip to content

worker.unref() doesn't make Node.js process exit depend on where worker.on('message') appears #53036

@toyobayashi

Description

@toyobayashi

Version

v20.12.0

Platform

Darwin toyobayashiM2Pro.local 23.4.0 Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:49 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6020 arm64

Subsystem

worker_threads

What steps will reproduce the bug?

  1. Create index.js

    process.once('beforeExit', () => {
      console.log('beforeExit')
    })
    
    const { Worker } = require('worker_threads')
    
    const w = new Worker(`
    const { parentPort } = require('worker_threads');
    parentPort.on('message', (msg) => {
      parentPort.postMessage(msg);
    });
    `, { eval: true })
    
    // w.on('message', () => {}) // <--- enable this line to let Node.js exit
    
    w.unref()
    
    w.on('message', () => {}) // <--- or comment this line to let Node.js exit
  2. Run node ./index.js

How often does it reproduce? Is there a required condition?

Always

What is the expected behavior? Why is that the expected behavior?

worker.unref() make Node.js exit no matter where worker.on('message', () => {}) appear.

What do you see instead?

Node.js process stuck forever.

Additional information

w.on('message', () => {})
w.unref()
w.on('message', () => {})
// ✅ exit
w.unref()
w.on('message', () => {})
// ❗️ stuck
w.on('message', () => {})
w.unref()
// ✅ exit
w.unref()
// ✅ exit

Not sure if this is expected behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    wontfixIssues that will not be fixed.workerIssues and PRs related to Worker support.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions