nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.44k stars 276 forks source link

When using worker_threads, code is not run executing as expected #4359

Closed qiaoshouzi closed 3 months ago

qiaoshouzi commented 3 months ago

Details

In my expectation, the example code should output like this.

> node index.js
start
test1
test3
test2

But in reality, the parentPort?.postMessage("...") seems to be executed first, so the output becomes like this.

> node index.js
start
test3
test2
test1

Is this a feature or a bug?

Node.js version

v20.10.0

Example code

// index.js
const { Worker } = require("node:worker_threads");
const path = require("node:path");

const main = async () => {
    const worker = new Worker(path.join(__dirname, "./worker/test.js"));
    worker.on("message", (v) => {
        console.log(v);
    });
    worker.postMessage("start");
};
main();
// /worker/test.js
const { parentPort } = require("node:worker_threads");

const startEvent = async () => {
  console.log("test1");
  parentPort?.postMessage("test3");
};

const main = async (v) => {
  console.log(v);
  await startEvent();
  parentPort?.postMessage("test2");
};

if (parentPort) {
  parentPort.on("message", main);
}

Operating system

Win10 22H2

Scope

other

Module and version

worker_threads

gireeshpunathil commented 3 months ago

@qiaoshouzi -

In my expectation, the example code should output like this.

you may not expect that ordering, it is neither specified nor documented.

explanation: when two threads run in parallel, the order in which they finish their execution may or may not be in the order in which the work was assigned or started. complex thread scheduling occur underneath. in addition, the console print is asynchronous, which means an issuance of console.log may not be delivered synchronously.

If maintaining a specific order is a priority, pls avoid multi-threading.

hope this helps!