gpt4 book ai didi

javascript - Node.JS 中的网络 worker 线程

转载 作者:搜寻专家 更新时间:2023-11-01 00:23:49 24 4
gpt4 key购买 nike

我是来自 C# 世界的 NodeJS 新手,仍在努力理解复杂的 JavaScript 迷宫。我正在尝试通过 https://www.npmjs.com/package/webworker-threads 上的示例实现多线程.

无法理解为什么下面的工作:

var Worker = require('webworker-threads').Worker;
var FibCalculator = require('./FibCalculator.js');

require('http').createServer(function (req,res) {
console.log('request received.');
var fibo = new Worker(function() {
var calcFib = function (n) {
return n > 1 ? calcFib(n - 1) + calcFib(n - 2) : 1;
};
this.onmessage = function (event) {
postMessage(calcFib(event.data));
};
});
fibo.onmessage = function (event) {
var msg = 'fib(5) = ' + event.data;
console.log(msg);
res.end(msg);
};
fibo.postMessage(5);
}).listen(3000);

但下面就是没有

var Worker = require('webworker-threads').Worker;
var FibCalculator = require('./FibCalculator.js');

//the below function just does not get called
var calcFib = function (n) {
console.log('***This will not print. Can someone explain why?***');
return n > 1 ? calcFib(n - 1) + calcFib(n - 2) : 1;
};

require('http').createServer(function (req,res) {
console.log('request received.');
var fibo = new Worker(function() {
this.onmessage = function (event) {
postMessage(calcFib(event.data));
};
});
fibo.onmessage = function (event) {
var msg = 'fib(5) = ' + event.data;
console.log(msg);
res.end(msg);
};
fibo.postMessage(5);
}).listen(3000);

为什么我去掉calcFib的作用域,就调用不了。我的想法是在 webworker-threads 上实现一个包装器,它可以用来在另一个线程上执行任何 CPU 内部操作。但是,我什至无法调用外部函数

以下是对本杰明格鲁恩鲍姆回答的回复:

我如何在 onmessage 中调用 console.log 而不是在同一个文件的作用域外定义的函数?

this.onmessage = function (event) {
console.log('can call console.log even if it is external');
//cannot call calcFib(event.data) if it is defined outside the scope.
postMessage(calcFib(event.data));
};

最佳答案

工作人员通过复制代码 来工作,因此所有闭包数据都将丢失。您无法从工作人员内部访问闭包范围,因此 calcFib 未定义。

您需要定义 calcFib inside worker 代码或通过消息发送它并对其进行eval

var Worker = require('webworker-threads').Worker;
var FibCalculator = require('./FibCalculator.js');

require('http').createServer(function (req,res) {
console.log('request received.');

var fibo = new Worker(function() {
//the below function just does not get called
var calcFib = function (n) {
console.log('***This will not print. Can someone explain why?***');
return n > 1 ? calcFib(n - 1) + calcFib(n - 2) : 1;
};
this.onmessage = function (event) {
postMessage(calcFib(event.data));
};
});
fibo.onmessage = function (event) {
var msg = 'fib(5) = ' + event.data;
console.log(msg);
res.end(msg);
};
fibo.postMessage(5);
}).listen(3000);

关于javascript - Node.JS 中的网络 worker 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30959252/

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