node.js 多线程库
我们都知道node.js是单线程,也就算服务器有多个cpu也只能使用到一个,虽然可以异步执行,可以把相对比较耗时的程序放到后面运行,但始终还是需要排队去执行。这样如果同时执行大量耗时的程序,那就难免不了会堵塞。
其实问题很简单,我们如何去充分利用服务器的多核cpu,让node.js实现多线程。分别将耗时的程序平均分配到每个cpu上运行,这样就大大提高效果,至少要保住主线程不要挂。
这里推荐一个微软开发的多线程模块:Napa.js
本人在mac上运行成功,安装步骤:
1,安装依赖
npm install -g cmake-js
更多系统依赖参看:https://github.com/Microsoft/napajs/wiki/build-napa.js
2,安装napajs
npm install napajs
https://github.com/Microsoft/napajs
案例:
var napa = require('napajs'); var zone1 = napa.zone.create('zone1', { workers: 4 }); // Broadcast code to all 4 workers in 'zone1'. zone1.broadcast('console.log("hello world");'); // Execute an anonymous function in any worker thread in 'zone1'. zone1.execute( (text) => text, ['hello napa']) .then((result) => { console.log(result.value); });
执行的效果是:
