这是我的工作者:
const Worker = require('worker_threads');
const worker = new Worker("function hello () { console.log('hello world');}", { eval: true })
worker.hello() // not correct
我想调用
hello()
函数。我该怎么做?
这是我的工作者:
const Worker = require('worker_threads');
const worker = new Worker("function hello () { console.log('hello world');}", { eval: true })
worker.hello() // not correct
hello()
函数。线程通过来回传递消息进行通信,例如:
worker.postMessage("say hello");
您的工作线程将为 message
事件设置一个监听器,并将该事件的 value
属性作为消息接收:
// In the worker
const { isMainThread, parentPort } = require('worker_threads');
if (!isMainThread) {
parentPort.on("message", e => {
// Dispatch here. For instance:
if (e.value === "say hello") {
hello();
}
};
}
function hello() { /*...*/ }
消息传递的内容远不止于此,请参阅工作线程文档以获取更多细节。
Worker
的方式。 - blex