如何从主线程发送输入到node js中的工作线程(Worker_threads)



我有一段代码我想在主线程中接受输入然后将其提供给工作线程所以我不必在工作线程中放入问题所以问题重复

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

你好,你可以使用Worker数据,所以发送变量

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

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

最新更新