UNPKG

workerhelp

Version:

基于Node.js worker_threads 的轻量级跨线程RPC通信模块,支持主线程与Worker线程之间的异步方法调用。

60 lines (51 loc) 1.98 kB
// 主线程逻辑 const { Worker, isMainThread, parentPort, workerData, threadId } = require('worker_threads'); const { Mutex } = require('./lock'); // 锁的状态:0=未锁定,1=锁定 const LOCKED = 1; const UNLOCKED = 0; if (isMainThread) { const sharedBuffer = new SharedArrayBuffer(4); // 4字节存储锁状态 const numWorkers = 4; let completedWorkers = 0; // 初始化锁状态为 UNLOCKED const initialLockView = new Int32Array(sharedBuffer); initialLockView[0] = UNLOCKED; // 启动 Worker 线程 for (let i = 0; i < numWorkers; i++) { let w = new Worker(__filename, { workerData: { sharedBuffer } }).on('message', (msg) => { if (msg.startsWith('done')) { console.log(w.threadId + '----- 线程完成' + msg) completedWorkers++; if (completedWorkers === numWorkers) { console.log('所有线程完成'); } } }); } // Worker 线程逻辑 } else { const { sharedBuffer } = workerData; const mutex = new Mutex(sharedBuffer); // 需要加锁的函数 const criticalSection = () => { try { mutex.lock(); // 获取锁 console.log(`Worker ${threadId} 加锁`); // 临界区代码(模拟耗时操作) for (let i = 0; i < 1000000; i++) { } process.stdout.write(`Worker ${threadId} 进入临界区\n`); } finally { process.stdout.write(`Worker ${threadId} 离开临界区\n`); mutex.unlock(); // 确保锁被释放 process.stdout.write(`Worker ${threadId} 释放锁\n`); } }; criticalSection(); console.log(`Worker ${threadId} 完成`) var p = Math.random().toFixed(3); console.log(`Worker ${threadId} 随机数:${p}`) parentPort.postMessage('done' + p); }