javascript / intermediate
Snippet
Offloading CPU Tasks with Worker Threads
Node.js worker threads allow parallel execution of JavaScript. This is essential for heavy calculations that would otherwise block the main Event Loop.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
const { Worker, isMainThread, parentPort } = require('node:worker_threads');if (isMainThread) {const worker = new Worker(__filename);worker.on('message', (result) => console.log('Result:', result));worker.postMessage(40);} else {parentPort.on('message', (num) => {const fib = (n) => (n <= 1 ? n : fib(n - 1) + fib(n - 2));parentPort.postMessage(fib(num));});}
nodejs
Breakdown
1
new Worker(__filename)
Spawns a new thread using the current file as the entry point.
2
parentPort.postMessage(...)
Sends data back from the worker thread to the main thread.