0
0
Node.jsframework~30 mins

Creating worker threads in Node.js - Try It Yourself

Choose your learning style9 modes available
Creating worker threads
📖 Scenario: You are building a Node.js application that needs to perform a heavy calculation without blocking the main program. To do this, you will use worker threads to run the calculation in the background.
🎯 Goal: Create a simple Node.js program that uses the worker_threads module to run a worker thread which calculates the sum of numbers from 1 to 1000000 and sends the result back to the main thread.
📋 What You'll Learn
Create a worker thread using the Worker class from the worker_threads module
Send a message from the main thread to the worker thread
Perform the sum calculation inside the worker thread
Send the result back from the worker thread to the main thread
💡 Why This Matters
🌍 Real World
Worker threads help Node.js applications perform CPU-heavy tasks without freezing the user interface or blocking other operations.
💼 Career
Understanding worker threads is important for backend developers to build scalable and responsive Node.js applications that handle intensive computations efficiently.
Progress0 / 4 steps
1
Import the worker_threads module and check if current thread is main
Write code to import Worker and isMainThread from the worker_threads module. Then create an if statement that checks if isMainThread is true.
Node.js
Need a hint?

Use require('worker_threads') to import Worker and isMainThread. Then write if (isMainThread) { ... } else { ... } to separate main and worker code.

2
Create a new Worker instance in the main thread
Inside the if (isMainThread) block, create a new Worker instance that runs the current file using __filename. Assign it to a variable called worker.
Node.js
Need a hint?

Create a Worker with new Worker(__filename) inside the main thread block.

3
Send a message from main thread and calculate sum in worker thread
In the main thread block, send a message { start: 1, end: 1000000 } to the worker using worker.postMessage(). In the else block (worker thread), listen for messages using parentPort.on('message', (data) => { ... }). Inside the listener, calculate the sum of numbers from data.start to data.end and send the result back using parentPort.postMessage(sum).
Node.js
Need a hint?

Use worker.postMessage() in main thread to send data. In worker thread, use parentPort.on('message', ...) to receive data and calculate sum with a for loop. Then send result back with parentPort.postMessage().

4
Receive and handle the result in the main thread
In the main thread block, add a listener for worker.on('message', (result) => { ... }) to receive the sum result from the worker. Inside the listener, assign the received result to a variable called totalSum.
Node.js
Need a hint?

Use worker.on('message', (result) => { ... }) in main thread to get the result and assign it to totalSum.