在 Node.js 中的工作线程中调用函数

5

这是我的工作者:

const Worker = require('worker_threads');
const worker = new Worker("function hello () { console.log('hello world');}", { eval: true })
worker.hello() // not correct

我想调用hello()函数。
我该怎么做?

如果您查看文档,您会发现这不是他们要求的Worker的方式。 - blex
1个回答

5

线程通过来回传递消息进行通信,例如:

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() { /*...*/ }

消息传递的内容远不止于此,请参阅工作线程文档以获取更多细节。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接