如何将输入从 MainThread 发送到节点 js 中的工作线程 (Worker_threads)
how to send input from the MainThread to the worker thread in 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'.
}
所以我有这段代码,我想在主线程中获取输入,然后将其提供给工作线程,这样我就不必将问题放在工作线程中,所以问题重复
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'.
}