【问题标题】:How to use worker threads in nodejs?如何在 nodejs 中使用工作线程?
【发布时间】:2020-09-21 10:16:22
【问题描述】:

我有以下代码,其中传递的数组长度太高并且处理每个数组元素需要一秒钟的时间,我如何在以下情况下使用工作线程?

function processData(arr){
    var result = [];
    for(var i = 0; i < arr.length; i++){
        result.push(process(arr[i]));
    }
    return result;
}

function process() {
    // some code here takes 1 second to execute
}

processData(arr);

【问题讨论】:

  • 你可以使用workerpool npm 包来做同样的事情

标签: node.js multithreading node-worker-threads


【解决方案1】:

你可以使用workerpool npm 包在工作线程中完成你的长时间处理工作,像这样

const workerpool = require('workerpool');

const pool =  workerpool.pool();

const arr = [...] // Large Data set which is to be processed

new Promise((resolve, reject) => {
  pool.exec(
    arr => {
      var result = [];
      for(var i = 0; i < arr.length; i++){
        /* 
        Do the long processing on data 
        */
        const processedData = a[i];
        result.push(processedData);
      }
      return result;
    },
    [arr]
  )
  .then(result => resolve(result))
  .catch(err => reject(err));
});

【讨论】:

  • 感谢@Aayush,如何处理在函数 process() 中我从其他文件调用函数的情况,例如 const util = require('./utils');那么我如何访问 pool.exec() 中的“util.calculate()”
  • 你发送给worker的数据是以序列化的形式发送的,因此你可以发送对函数和对象的引用,但是workerpool内部的函数不会与外部世界对象通信。在这里查看npmjs.com/package/workerpool#offload-functions-dynamically
  • 所以我很难在单个函数 process() 中添加所有内容以满足此标准。有没有其他方法可以解决这个问题?
猜你喜欢
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
  • 2020-02-25
  • 1970-01-01
  • 2013-11-16
  • 2021-03-19
  • 1970-01-01
相关资源
最近更新 更多