更新日期:2024-03-25
版本:1.1.0
更新内容:
- 新增子线程监听事件
index.ts
import { WorkerPool } from "dl-worker"; // 或 import WorkerPool from "dl-worker";
const path = require("path");
// 初始化线程池配置,并返回线程池实例
const createTest = WorkerPool.init({
key: "test",
size: 2,
scriptPath: path.join(__dirname, "/worker.js"),
argument: {
param: "全局参数6666666",
},
});
// 获取线程池实例,等同于 createTest 实例
const test = WorkerPool.getWorker("test");
// 线程结束
test.on("exit", (value) => {
console.log("exit", value);
});
// 线程错误
test.on("error", (value) => {
console.log("error", value);
});
let count = 0;
for (let i = 0; i < 10; i ) {
// 执行任务
test.runTask({ id: "100" i, money: 288 }, (resp) => {
count = 1;
// 执行结果
console.log(`任务执行${count}===`, resp);
// 完成所有任务
if (count == 10) {
console.log("任务执行完成");
// 销毁线程池释放资源
test.destroy();
}
});
}
worker.ts
import { WorkerPool } from "dl-worker"; // 或 import WorkerPool from "dl-worker";
import { workerData } from "worker_threads";
// data 为接收到runTask方法的第一个参数
WorkerPool.on("message", function (data) {
console.log("接收到了主线程参数:", data);
// 打折
data.money = (data.money * Math.random()).toFixed(2) "元";
// 发送处理结果给主进程里的runTask的’callback‘方法回调
this.postMessage(data);
});
WorkerPool.on("messageerror", (error) => {
console.log("接收到了错误信息:", error);
});
WorkerPool.on("close", () => {
console.log("当前进程关闭了");
});
console.log("初始化完成");
console.log("获取全局变量:", workerData);