![](/img/trans.png)
[英]Is it possible to make an async renderToString with worker_threads?
[英]Processing a multidimensional array with worker_threads
我有一个有趣的任务,但我什至在学习工人方面感到困惑。 有一个尺寸为 10-30K 对象的数组。 我想把它分成可用流数和每个子数组中的子数组,以实现在某些字段中搜索所需对象的功能。
关于将数组划分为子数组的问题以及搜索功能的实现 - 一切都很好。 但是如何在每个子阵列中同时在worker的帮助下开始搜索——有麻烦(
我刚开始认识工人,并没有完全了解一切。 我将不胜感激您的帮助或建议。
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));
出于这种目的,您可以查看专为此类内容构建的microjob lib。
这是您的上下文示例(它使用 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.