[英]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'.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.