调用工作线程nodejs内部的函数



这是我的工作人员:

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事件设置一个侦听器,并将消息作为eevnt:的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() { /*...*/ }

来回传递消息还有很多,详细信息请参阅工作人员文档。

最新更新