Worker Threads enable true parallelism in Node.js, perfect for CPU-intensive tasks. Let's dive in.
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);
Worker Threads shine for parallel processing of CPU-intensive tasks. Use wisely to supercharge your Node.js applications.
Cheers?
以上是Unleashing Parallel Processing with Node.js Worker Threads的详细内容。更多信息请关注PHP中文网其他相关文章!