piscina nodejs woker 线程池实现

nodejs 线程池工具还是很多的,piscina 是一个比较活跃的项目

包含的特性

  • 快速
  • 包含了固定以及可变任务场景
  • 支持灵活的线程池大小
  • 异步追踪支持
  • 取消支持
  • 支持comonj,esm,以及ts
  • 自定义任务队列
  • linux 系统上可选的cpu 调度支持

参考使用

  • app.js
const path = require('path');
const Piscina = require('piscina');
 
const piscina = new Piscina({
  filename: path.resolve(__dirname, 'worker.js')
});
 
(async function() {
  const result = await piscina.run({ a: 4, b: 6 });
  console.log(result);  // Prints 10
  // 通过代码加载文件
  const resultv2 = await piscina.run({ a: 4, b: 100 },{filename: path.resolve(__dirname, 'as.js')});
  console.log(resultv2);  // Prints 10
})();
  • woker.js
module.exports = ({ a, b }) => {
    return a + b;
};
  • as.js
const { setTimeout } = require('timers/promises');
 
module.exports = async ({ a, b }) => {
  // Fake some async activity
  await setTimeout(1000);
  return a + b;
};
  • 多方法支持
    注意参数传递应该是一个对象
    比如rong.js
 
function add({ a, b }) { return a + b; }
 
function multiply({ a, b }) { return a * b; }
 
module.exports = {
    add,
    multiply
};

说明

tinypool 是一个fork自piscina 的一个项目,移除了一些不需要的功能

参考资料

https://www.npmjs.com/package/tinypool
https://github.com/poolifier/poolifier
https://github.com/piscinajs/piscina
https://www.npmjs.com/package/worktank

posted on   荣锋亮  阅读(375)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-11-22 golang 一些不错的log 包
2020-11-22 mysql_fdw 集成go-mysql-server 开发的mysql server
2020-11-22 一些不错的golang web 框架
2020-11-22 golang gomail+fasttemplate+mailhog 发送邮件
2020-11-22 golang go-simple-mail+fasttemplate+mailhog 发送邮件
2019-11-22 cube.js 最近的一些更新
2018-11-22 续drone 1.0 新界面调整

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示