工作執行緒在 Node.js 中實現真正的平行性,非常適合 CPU 密集型任務。讓我們深入了解一下。
const { Worker, isMainThread, parentPort } = require('worker_threads'); if (isMainThread) { const worker = new Worker(__filename); worker.on('message', (msg) => console.log('From worker:', msg)); worker.postMessage('Hello, Worker!'); } else { parentPort.on('message', (msg) => { console.log('From main:', msg); parentPort.postMessage('Hello, Main!'); }); }
const { Worker } = require('worker_threads'); const worker = new Worker('./worker.js'); const sharedBuffer = new SharedArrayBuffer(4); const arr = new Int32Array(sharedBuffer); arr[0] = 123; worker.postMessage({ sharedBuffer });
const { StaticPool } = require('node-worker-threads-pool'); const pool = new StaticPool({ size: 4, task: (n) => n * 2 }); async function runTasks() { const results = await Promise.all([ pool.exec(10), pool.exec(20), pool.exec(30) ]); console.log(results); // [20, 40, 60] } runTasks().catch(console.error);
工作執行緒在並行處理 CPU 密集型任務方面表現優異。明智地使用來增強您的 Node.js 應用程式。
乾杯?
以上是使用 Node.js 工作執行緒釋放並行處理能力的詳細內容。更多資訊請關注PHP中文網其他相關文章!