Search code examples
javascriptnode.jsmultithreadingmultiprocessingworker-thread

how to send input from the MainThread to the worker thread in node js (Worker_threads)


so i have this piece of code that i want to take the input in the main thread and then feed it to the worker threads so i dont have to put the question in the worker thread so the question repeat

const { Worker, isMainThread } = require('worker_threads');
if (isMainThread) {
let x = prompt("question")
for (let i = 0; i < 2; i++) {
    new Worker(__filename,);
    }
  // This re-loads the current file inside a Worker instance.
} else {

console.log(x)
  console.log('Inside Worker!');
  console.log(isMainThread);  // Prints 'false'.
}

Solution

  • Hello you can use Worker data so send the variable

    const { Worker, isMainThread ,workerData } = require('worker_threads');
    
        if (isMainThread) {
          x = "hello world" ;
        for (let i = 0; i < 1; i++) {
            new Worker(__filename,{ workerData: x });
            }
          // This re-loads the current file inside a Worker instance.
        } else {
          
        console.log(workerData)
          console.log('Inside Worker!');
          console.log(isMainThread);  // Prints 'false'.
        }
    

    EDIT 1

    to be able to send multiple variables you can assign the workerdata to a Json something like this. 
    const {
      Worker,
      isMainThread,
      workerData,
      SHARE_ENV,
    } = require("worker_threads");
    if (isMainThread) {
      x = "hello world";
      let y = "hello";
      for (let i = 0; i < 1; i++) {
        new Worker(__filename, {
          workerData: {
            x: x,
            y: sun,
          },
        });
      }
      //) This re-loads the current file inside a Worker instance.
    } else {
      console.log(workerData.y);
      console.log("Inside Worker!");
      console.log(isMainThread); // Prints 'false'.
    }