运行昂贵的异步exec调用时,NodeJS循环会大大减慢速度吗?

时间:2019-03-06 07:13:56

标签: node.js multithreading exec

我在使用NodeJS应用程序时遇到了麻烦。该应用程序的要旨是:该应用程序通过chokidar在受监视的目录中检测到文件添加(分层/金字塔TIFF)。检测到后,此文件名将添加到MariaDB(通过mysql模块),并用“状态”和“步骤”列标记。

然后,每隔一秒钟,甚至2-5秒(全部尝试),我轮询SQL(小表,在LAN上,没什么大不了的)以获取处理每个文件的状态。然后,执行以下步骤:调用VIPS库以创建金字塔图像,或调用ImageMagick提取或转换图像的一部分。其中一些命令可能需要几分钟的时间才能使用CPU。

该程序会非常迅速地大大降低速度。甚至在exec进程不再显示在顶部之后/已经退出。有什么想法吗?是因为完全不了解异步执行程序应该如何工作?

骨架代码如下(简化,忽略错误处理等):

doStep1 = function(rows) {
  _.each(rows, function(r) {
  if (I'm not already running more than N of these processes) {
    running_processes++
    return database.markAsInProgress().then(function() {
      return new Promise(function(req, res) {
        exec('some image processing command ' + r.filename, function(err, stdout) {
          running_processes--
          res(let's just say success)
        })
      })
    }).then(function() {
      return database.markAsStepComplete()
    })
  }
}

setInterval(function() { database.getActiveFiles().then(function(rows) { 
  doStep1(_.filter(rows, function(el) { return meets some mutually exclusive criteria; }))
  doStep2(_.filter(rows, function(el) { return meets some mutually exclusive criteria; }))
  ...
  doStepN(...)
}, 1000)

0 个答案:

没有答案