0

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'.
}

1 Answer 1

1

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'.
}
Sign up to request clarification or add additional context in comments.

1 Comment

i tried this one and it worked, but what if i want to send multiple values from the main thread ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.