worker.js

var cluster = require('cluster')
function fibo(n) {
return n == 0 ? 0 : n > 1 ? fibo(n - 1) + fibo(n - 2) : 1
}
console.log(`worker ${cluster.worker.id} start...`)
process.on('message',msg=>{
console.log(` ${cluster.worker.id} receive data is ${msg}`)
var st = Date.now()
console.log(`worker ${cluster.worker.id} start to work`)
var result = fibo(msg)
console.log(`worker ${cluster.worker.id} finish work and using ${Date.now() - st} ms`)
process.send(result)
})

master.js

module.exports = exuteFibo

function exuteFibo() {
return (new Promise((reslove, reject) => {
var cluster = require('cluster')
const numCpus = require('os').cpus().length
var result = []
var workerID = []
cluster.setupMaster({
exec: '../worker.js',
slient: true
})
if (cluster.isMaster) {
var collection = [41, 41, 41, 41]
var st = Date.now()
for (let i = 0; i < numCpus; i++) {
var wk = cluster.fork()
workerID.push(wk.id)
wk.send(collection[i])
}
cluster.on('fork', worker => {
if (workerID.includes(worker.id)) {
console.log(`[master]: fork worker ${worker.id}`)
}
})
cluster.on('exit', (worker, code, signal) => {
console.log(`[master]:worker ${worker.id} died`)
})
var numCount = 0
Object.keys(cluster.workers).forEach(id => {
cluster.workers[id].on('message', msg => {
console.log(`[master] receive message from [worker ${id}]:${msg}`)
result.push(msg)
numCount++
if (numCount == collection.length) {
console.log(`master finish all work adn using ${Date.now() - st} ms`)
workerID.forEach(function(id) {
if (!cluster.workers[id].exitedAfterDisconnect) {
cluster.workers[id].disconnect();
}
})
reslove(result)
}
})
})
}
}))
}

testMaster.js

var exuteFibo = require('./masterFinal.js')
console.log('====start=======')
var st = Date.now()

exuteFibo().then(rs => {
console.log(`Finish all work and using ${Date.now()-st}`)
console.log('####Get result from multipe-processes:' + rs)
})

st = Date.now()

exuteFibo().then(rs => {
console.log(`Finish all work and using ${Date.now()-st}`)
console.log('####Get result from multipe-processes:' + rs)
})

运行结果:

====start=======

[master]: fork worker 1

[master]: fork worker 2

[master]: fork worker 3

[master]: fork worker 4

[master]: fork worker 5

[master]: fork worker 6

[master]: fork worker 7

[master]: fork worker 8

worker 4 start...

worker 1 start...

4 receive data is 41

worker 4 start to work

worker 2 start...

worker 3 start...

1 receive data is 41

worker 1 start to work

2 receive data is 41

worker 2 start to work

worker 5 start...

5 receive data is 41

worker 5 start to work

3 receive data is 41

worker 3 start to work

worker 6 start...

6 receive data is 41

worker 6 start to work

worker 7 start...

7 receive data is 41

worker 7 start to work

worker 8 start...

8 receive data is 41

worker 8 start to work

worker 4 finish work and using 9574 ms

[master] receive message from [worker 4]:165580141

[master] receive message from [worker 4]:165580141

worker 7 finish work and using 9519 ms

[master] receive message from [worker 7]:165580141

worker 6 finish work and using 9652 ms

[master] receive message from [worker 6]:165580141

worker 1 finish work and using 9732 ms

[master] receive message from [worker 1]:165580141

[master] receive message from [worker 1]:165580141

master finish all work adn using 9956 ms

Finish all work and using 9957

####Get result from multipe-processes:165580141,165580141,165580141,165580141

[master]:worker 6 died

[master]:worker 6 died

[master]:worker 7 died

[master]:worker 7 died

worker 2 finish work and using 9778 ms

[master] receive message from [worker 2]:165580141

[master] receive message from [worker 2]:165580141

worker 5 finish work and using 9780 ms

[master] receive message from [worker 5]:165580141

[master]:worker 5 died

[master]:worker 5 died

worker 3 finish work and using 9798 ms

[master] receive message from [worker 3]:165580141

master finish all work adn using 10044 ms

[master] receive message from [worker 3]:165580141

Finish all work and using 10033

####Get result from multipe-processes:165580141,165580141,165580141,165580141

[master]:worker 4 died

[master]:worker 4 died

[master]:worker 1 died

[master]:worker 1 died

[master]:worker 2 died

[master]:worker 2 died

[master]:worker 3 died

[master]:worker 3 died

worker 8 finish work and using 9192 ms

[master] receive message from [worker 8]:165580141

[master]:worker 8 died

[master]:worker 8 died

node cluster模块,仿多线程并发调用,的更多相关文章

  1. node cluster模块的使用和测试

    首先安装async包 用到的有http.cluster包 http和cluster都会node自带的包,无需安装 1:创建cluster.js,代码如下,更具cpu创建多个进程 var cluster ...

  2. Python Socket多线程并发

    1.SocketServer模块编写的TCP服务器端代码 Socketserver原理图 服务端: import SocketServer #导入SocketServer,多线程并发由此类实现 cla ...

  3. Java并发编程 (十) 多线程并发拓展

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 一.死锁 1.死锁的定义 所谓的死锁是指两个或两个以上的线程在等待执行的过程中,因为竞争资源而造成的一种 ...

  4. 【nodejs原理&源码赏析(4)】深度剖析cluster模块源码与node.js多进程(上)

    [摘要] 集群管理模块cluster浅析 示例代码托管在:http://www.github.com/dashnowords/blogs 一. 概述 cluster模块是node.js中用于实现和管理 ...

  5. 【nodejs原理&源码赏析(4)】深度剖析cluster模块源码与node.js多进程(上)

    目录 一. 概述 二. 线程与进程 三. cluster模块源码解析 3.1 起步 3.2 入口 3.3 主进程模块master.js 3.4 子进程模块child.js 四. 小结 示例代码托管在: ...

  6. 【nodejs原理&源码赏析(6)】深度剖析cluster模块源码与node.js多进程(下)

    [摘要] cluster模块详解 示例代码托管在:http://www.github.com/dashnowords/blogs 阅读本章需要先阅读本系列前两章内容预热一下. 一. 引言 前两篇博文中 ...

  7. 【nodejs原理&源码赏析(6)】深度剖析cluster模块源码与node.js多进程(下)

    目录 一. 引言 二.server.listen方法 三.cluster._getServer( )方法 四.跨进程通讯工具方法Utils 五.act:queryServer消息 六.轮询调度Roun ...

  8. Node.js的cluster模块——Web后端多进程服务

    众所周知,Node.js是单线程的,一个单独的Node.js进程无法充分利用多核.Node.js从v0.6.0开始,新增cluster模块,让Node.js开发Web服务时,很方便的做到充分利用多核机 ...

  9. C# 防止同时调用=========使用读写锁三行代码简单解决多线程并发的问题

    http://www.jb51.net/article/99718.htm     本文主要介绍了C#使用读写锁三行代码简单解决多线程并发写入文件时提示"文件正在由另一进程使用,因此该进程无 ...

随机推荐

  1. python提取文件中的方法名称

    #提取文件中的方法名称 # -*- coding:utf-8 -*- def Query_Method(filepath): file = open(filepath,'r',encoding= 'U ...

  2. springcloud Eureka控制台参数说明

    Home进入Eureka控制台首页,首先看HOME页的头部 System Status Environment : 环境,默认为test, 该参数在实际使用过程中,可以不用更改 Data center ...

  3. UI开发总结

    1. bootstrap tooltip 修改内容 <i class="ace-icon fa fa-user" id="test-tooltip" ti ...

  4. 使用asp.net MVC的 HtmlHelper 时遇到的小问题,报错:Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

    异常信息:Templates can be used only with field access, property access, single-dimension array index, or ...

  5. 20165206 2017-2018-2《Java程序设计》课程总结

    20165206 2017-2018-2<Java程序设计>课程总结 一.每周作业链接汇总 预备作业1:对师生关系的看法和期望 预备作业2:c语言基础和学习技能的理解 预备作业3:Linu ...

  6. python 通用装饰器,带有参数的装饰器,

    # 使用装饰器对有返回值的函数进行装饰# def func(functionName): # print('---func-1----') # def func_in(): # print(" ...

  7. MySQL:日期函数、时间函数总结

    MySQL 获得当前日期时间 函数 查询昨天,时间拼接 select concat(DATE_FORMAT(date_add(now(), interval -1 day),'%Y-%d-%d'),& ...

  8. Visual Studio 2017离线安装失败:安装程序清单签名验证失败

    解决办法: 方法1:运行gpeidit.msc,然后  Windows 设置-安全设置->本地策略-安全选项-系统机密->将FIPS兼容算法用于加密.哈希和签名-设置禁用 方法2:删除vs ...

  9. cuda by example【读书笔记2】

    常量内存 用常量内存来替换全局内存可以有效的减少内存带宽 __constant__修饰符标识常量内存,从主机内存复制到GPU上的常量内存时,需要特殊版本的cudaMemcpy(): cudaMemcp ...

  10. Windows10上强制Visual Studio以管理员身份运行

    解决办法很简单: 1. 打开VS的安装目录,找到devenv.exe,右键,选择“兼容性疑难解答”. 2. 选择“疑难解答程序” 3. 选择“该程序需要附加权限” 4. 确认用户帐户控制后,点击测试程 ...