简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM