Call iterator (object | arr, tr: number of threads) return loop (callback, the callback)
Iterator (arr,5). Loop (function(){return val // returns the result to the second callback function}, Function (val){// This function receives the result of the child thread})
Const {isMainThread, Worker, // MessagePort, parentPort, // MessageChannel, // workerData // null, } = require(‘ worker_Threads ‘);
const call=()=>{ return 1 }
Function iterator (arr,tr=3) {function iterator (arr,tr=3) {
const destructor = (arr) => { let newArr = [] const flat = (arr)=>{ Object.keys(arr).forEach(key => { let val = arr[key] if (typeof val === ‘object’) { flat(val) } else { if(val){ newArr.push(val) }
}
})
}
flat(arr)
return newArr
Copy the code
}
Const sliceTask = (newArr)=>{// Slices from threads const total = newarr. length const slices = total/tr const task=[] let start=0 for (let block = 0; block < tr; block++) { task.push(newArr.slice(start, start+slices)) start = start + slices }
return task
Copy the code
} const tasks = sliceTask(newArr) // Debugger return {loop (callback,send) {
tasks.forEach(task=>{ if (isMainThread) { const worker = new Worker(__filename); //let value = val worker.once('message', (val) => { send(val) worker.terminate() }); worker.postMessage({task,callback:callback.toString()}) } else { parentPort.once('message', Const arr=[] task.forEach(val => {// eval(' ${callback}; callback('received:' + ${val})`) const res= eval('(' + callback+ ')'+ '(val)') // const res=call() arr.push(res) //callback('received:' + val) }) parentPort.postMessage(arr); }); }})}Copy the code
}
}
console.time(‘a’) const arr=[1, 2, [3, [4, [5, 6, [{ key: ‘haah’, ri: ‘hehe’ }, 8]]]], 9, [10, [11, [12, [13]]]],].concat(array. from({length:1000},(item)=>23)) //* Pass an object or arr, the second is the number of threads // then call the loop iterator(arr,3) // loop The first callback must not be an arrow function, and the second callback must receive the result of the thread calculation. Loop (function (value) {
// console.log(value) Return value},(val)=>{// This function evaluates the function above to an array console.log(val)})
console.timeEnd(‘a’)
// const arr=[0]
// for(let key=0; key< arr.length; key++){ // arr.push(1) // } // console.log(arr)