Skip to content

Only a single console.log is logged from a worker when exiting #40961

@kripken

Description

@kripken

Version

16.5.0

Platform

Linux64

Subsystem

No response

What steps will reproduce the bug?

Testcase:

const {
  Worker, isMainThread
} = require('worker_threads');

if (isMainThread) {
  console.log('main');
  const worker = new Worker(__filename, {});
} else {
  console.log('worker1');
  console.log('worker2');
  console.log('worker3');
  process.exit(0);
}

Run with node b.js

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

100% of the time.

What is the expected behavior?

I would expect to see

main
worker1
worker2
worker3

What do you see instead?

main
worker1

The main thread logged, but the worker only logged the first of three loggings.

Additional information

Somehow the first console.log is always logged out, but the other ones are stopped by the presence of the process.exit after them. This does not seem to be a race in my testing: the first one is always shown, and none of the others.

Returning to the main event loop after the first logging allows one more logging to show up. That is:

const {
  Worker, isMainThread
} = require('worker_threads');

if (isMainThread) {
  console.log('main');
  const worker = new Worker(__filename, {});
} else {
  console.log('worker1');
  setTimeout(() => { // return to main event loop after first logging
    console.log('worker2');
    console.log('worker3');
    process.exit(0);
  }, 0);
}

That prints out worker2. Once more a single logging appears of all those that are expected to happen, and worker3 is not logged.

This was noticed in Emscripten here: emscripten-core/emscripten#14804 Emscripten will use process.exit when the program is done, and we were only getting the first console.log out of all those the program prints. (As a workaround we write synchonously to the fd for stdout, which does work.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    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