简体   繁体   English

使用 worker_threads 处理多维数组

[英]Processing a multidimensional array with worker_threads

I have an interesting task, but I was even confused in learning workers.我有一个有趣的任务,但我什至在学习工人方面感到困惑。 There is an array of dimensions of 10-30K objects.有一个尺寸为 10-30K 对象的数组。 I want to break it into subarrays in the number of available streams and in each subarray to implement the function of searching for the desired object in certain fields.我想把它分成可用流数和每个子数组中的子数组,以实现在某些字段中搜索所需对象的功能。

With the question of partitioning the array into subarrays and the implementation of the search function - all is well.关于将数组划分为子数组的问题以及搜索功能的实现 - 一切都很好。 But how to start a search with the help of workers simultaneously in each subarray - there are troubles (但是如何在每个子阵列中同时在worker的帮助下开始搜索——有麻烦(

I just began to get acquainted with the workers and did not fully understand everything.我刚开始认识工人,并没有完全了解一切。 I would be grateful for the help or advice.我将不胜感激您的帮助或建议。

PS Executing the code I get an error PS 执行代码我得到一个错误

function evalInWorker(f){
    if (isMainThread){
        return new Promise((res, rej) =>{
            const worker = new Worker(__filename, {eval: true});
            worker.on('error', e => rej(e));
            worker.on('message', msg => {
                res(msg);
            });
            worker.on('exit', code => {
                if(code !== 0)
                    rej(new Error(`Worker stopped with exit code ${code}`));
            });
        });
    }else {
        parentPort.postMessage(f());
    }
}
//getSlicedArr возвращает массив с подмассивами, search - ищет в подмассиве объект по нужным свойствам needToFind
const tasks = (threads, dataArr, needToFind, arr = \[\]) => {
    getSlicedArr(dataArr, threads).map( e => arr.push(evalInWorker(search(e, needToFind))));
    return arr;
};

Promise.all(tasks(subArrSize, dataArr, needToFind))
    .then(messList => {
        messList.forEach(m => console.log(m))
    })
    .catch(e => console.log(e));

在此处输入图片说明

For this kind of purpose, you can take a look to microjob lib that has been built exactly for this kind of stuff.出于这种目的,您可以查看为此类内容构建的microjob lib。

Here's an example with your context (it uses Typescript but it is the same with JS:这是您的上下文示例(它使用 Typescript 但它与 JS 相同:

import { start, stop, job } from 'microjob';

const main = async () => {
  await start();

  // build an array of 5 arrays filled with random numbers
  const table = Array.from({ length: 5 }).map(_ => Array.from({ length: 100 }).map(Math.random));

  // this is your search function (just a placeholder here)
  const search = (arr: number[]): number => {
    console.log(arr);

    return arr[0];
  };

  // job executes the search function inside a new thread
  // so the executions are made in parallel
  const res = await Promise.all(table.map(data => job(search, { data })));
  console.log(res);

  await stop();
};

main();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM