gpt4 book ai didi

javascript - Node.js 移动繁重的 CPU 密集型任务

转载 作者:行者123 更新时间:2023-11-28 05:31:26 27 4
gpt4 key购买 nike

我有一个函数,它根据传递的参数递归地调用自身。该函数在最后调用另一个函数,该函数可能非常耗费 CPU 资源,因为它处理一组 N 个对象并进行大量的字符串操作。当 N 足够大时,它会减慢应用程序的速度。使用计时器将字符串操作移至事件循环是行不通的,因为它仍然会减慢应用程序执行此循环后的代码的速度。我想过使用 child_process 生成另一个 Node 实例,但我认为这也不是一个好的解决方案,因为根据传递给第一个函数的配置,可以多次调用该函数,这意味着很多生成的 Node.js 进程。

下面是说明问题的代码示例:

function Fun(opts) {
// depending on opts we call HeavyCPU alot
while (...) {
var set = ...;
HeavyCPU(set)
}
}

function HEAVYCPU(var set) {
// Heavy CPU task - string manipulations
}

module.exports = Fun;

如果我以这种方式生成子进程:

// fun.js
var cp = require('child_process');
function Fun(opts) {
// depending on opts we call HeavyCPU alot
while (...) {
var set = ...;
var child = cp.fork('./heavycpu', set);
}
}

module.exports = Fun;

// heavycpu.js
function HEAVYCPU(var set) {
// Heavy CPU task - string manipulations
}

我仍然可能会产生大量生成的进程,具体取决于 while 语句,该语句依赖于 opts

遇到这种情况我该怎么办?

最佳答案

为了防止多次生成子进程,您可以格式化参数并在 HEAVYCPU(您的子任务)中调用 while 进程。

fun.js

var cp = require('child_process');
function Fun(opts) {
var arguments = processOptions(opts) //processOptions is just an example
var child = cp.fork('./heavycpu', arguments );
}

module.exports = Fun;

heavycpu.js

function HEAVYCPU(var set) {
while(...) {
//Here goes the actual processing code
}
}

如果您不想将 HEAVYCPU 代码与迭代参数混合在一起,您可以创建一个包装函数(然后在子进程中调用),该函数处理提供的参数,然后调用 HEAVYCPU.

您还可以将每个参数发送到您的进程:

The child_process.fork() method is a special case of child_process.spawn() used specifically to spawn new Node.js processes. Like child_process.spawn(), a ChildProcess object is returned. The returned ChildProcess will have an additional communication channel built-in that allows messages to be passed back and forth between the parent and child. See child.send() for details.

Child Processes Documentation

关于javascript - Node.js 移动繁重的 CPU 密集型任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671374/

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