Cha*_*ord 8 multithreading function cluster-computing worker node.js
所以我正在开发Node.js中的一个项目,我想打开一些额外的线程来更有效地处理处理负载.但是我正在使用带有函数定义的类,当我尝试将这些对象发送到工作线程时,对象中定义的函数会消失,而我只剩下对象中的其他字段.有没有办法向worker发送一个对象并保留这些函数,以便可以在worker中调用它们?
var cluster = require('cluster');
if(cluster.isMaster){
Monster = function(species){
this.attack = function(){
console.log('CHOMP');
};
this.name = species;
};
var vamp = new Monster('vampire'),
worker = cluster.fork();
worker.send({'monster' : vamp});
}
else{
process.on('message', function(msg) {
console.log(msg.monster); //this logs "{ name: 'vampire' }"
msg.monster.attack(); //TypeError: Object #<Object> has no method 'attack'
});
}
Run Code Online (Sandbox Code Playgroud)
不,没有办法在线程之间传递函数。您只能传递 JS 普通对象(仅数据)并使用当前线程中定义的函数处理它(例如使用接收到的数据创建新对象)。
归档时间: |
|
查看次数: |
3404 次 |
最近记录: |