UNPKG

process-worker-executor

Version:

将多进程和多线程封装为统一的 Async/Await 调用方式, 简化 IPC 消息通信的复杂性

30 lines (27 loc) 890 B
const { join } = require('path') const Executor = require('../Executor') const { Worker } = require('worker_threads') class WorkerExecutor extends Executor { #worker async onInit() { const modulePath = join(__dirname, 'WorkerExecutorLoder.js') const worker = new Worker(modulePath, { workerData: { logPath: this.logPath, logFile: this.logFile }, name: this.name }) worker.on('message', this.on.bind(this)) worker.on('exit', this.close.bind(this)) this.#worker = worker this.disposable.push(() => { worker.terminate() }) this.logger?.info('创建线程成功, 线程: %s', worker.threadId) } async onSend(data) { this.#worker.postMessage(data) } } module.exports = WorkerExecutor