只是用来学习多进程的没有任何实际意义,因为没有记忆优化慢的一批
代码
import cluster from "cluster"
import * as os from "os"
const cpu = os.cpus()
// console.log(cpu)
const fbi = (num:number):number=>{
switch (num){
case 0:
return 0
case 1:
return 1
default:
return fbi(num-1) + fbi (num-2)
}
}
if (cluster.isPrimary) {
const argNum = Number.parseInt(process.argv[2])
console.log("主线程已启动,请在启动参数中添加运算个数")
cluster.on('message',(wk,me,han)=>{
console.log(`运算斐波那契第${me.num}位,结果是${me.ret}`)
})
const addChild = async (i:number)=>{
return new Promise<void>((res,rej)=>{
res()
rej()
console.log(`-添加了${i}子进程运算任务`)
cluster.fork({num:i})
})
}
let tasks:Promise<void>[] = []
for (let i = 0; i <= argNum; i++) {
tasks.push(addChild(i))
}
await Promise.all(tasks)
}else{
const ComNum = Number.parseInt(process.env.num as unknown as string)
if(process.send){
process.send({num:ComNum,ret:fbi(ComNum)})
}
process.exit(0)
}