gpt4 book ai didi

javascript - 在nodejs工作线程内调用函数

转载 作者:行者123 更新时间:2023-12-02 21:14:50 25 4
gpt4 key购买 nike

这是我的 worker :

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

来回消息传递还有很多内容,详细信息请参见 the worker documentation .

关于javascript - 在nodejs工作线程内调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60998358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com