Har*_*rry 5 javascript node.js
这是我的工人:
const Worker = require('worker_threads');
const worker = new Worker("function hello () { console.log('hello world');}", { eval: true })
worker.hello() // not correct
Run Code Online (Sandbox Code Playgroud)
我想打电话hello()
我该怎么做呢?
线程通过来回传递消息进行通信,例如:
worker.postMessage("say hello");
Run Code Online (Sandbox Code Playgroud)
您的工作人员将为该事件设置一个侦听器message,并接收消息作为value该 eevnt 的属性:
// 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() { /*...*/ }
Run Code Online (Sandbox Code Playgroud)
来回消息传递还有很多内容,详细信息请参阅工作人员文档。