पाठ 19 / 30
CPU-Bound Work और Worker Threads
CPU-भारी काम को worker threads में भेजकर event loop को responsive रखें, और जानें कि clusters या processes से कब scale करना है।
Event loop को block करना
Non-blocking I/O तेज़ है, लेकिन लंबी synchronous गणना (image resize, hashing, बड़ा JSON parse) बाकी सभी requests को block कर देती है। CPU-bound काम main thread से बाहर होना चाहिए।
Worker threads
worker_threads अलग thread में script चलाता है और उससे messages का आदान-प्रदान करता है।
// main.js
import { Worker } from "node:worker_threads";
const worker = new Worker(new URL("./heavy.js", import.meta.url), { workerData: 40 });
worker.on("message", (result) => console.log("fib:", result));
worker.on("error", console.error);
// heavy.js
import { parentPort, workerData } from "node:worker_threads";
const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
parentPort.postMessage(fib(workerData));Workers का उपयोग CPU-bound jobs के लिए करें, I/O के लिए नहीं जो पहले से async है। Server को multi-core पर scale करने के लिए load balancer के पीछे कई processes (cluster या process manager) चलाएँ।