Welcome to the Node.js Worker Threads Tutorial! In this comprehensive guide, we'll dive into the world of multi-threading in Node.js. We'll explore how worker threads can help you handle CPU-intensive tasks and improve your application's performance.
By the end of this tutorial, you'll understand the basics of worker threads, learn how to create, manage, and communicate with them, and see practical examples that demonstrate their real-world usage.
Worker threads are independent units of execution that run concurrently with the main thread. They allow Node.js to perform multiple tasks simultaneously, improving the responsiveness and performance of your application.
To create a worker thread in Node.js, we use the worker_threads module. Let's start by creating a worker.
const { Worker, isMainThread } = require('worker_threads');
if (isMainThread) {
// Main thread code
const worker = new Worker('./worker.js');
} else {
// Worker thread code
// ...
}In this example, we import the worker_threads module and create a new worker by instantiating the Worker class. The worker thread code will be in a separate file (worker.js).
To communicate between the main thread and the worker thread, we can use postMessage() and on('message') events. Here's an example:
// worker.js
postMessage('Hello from worker');
// main.js
worker.on('message', message => {
console.log(message); // 'Hello from worker'
});What is the purpose of worker threads in Node.js?
In this tutorial, we've explored worker threads in Node.js, learned how to create and manage them, and seen examples of communication between the main thread and worker threads. In the next lesson, we'll delve deeper into worker threads, looking at advanced topics such as worker thread pools and error handling.
Stay tuned and happy coding! 🎉
In this example, we'll create a worker thread pool that can handle multiple tasks concurrently.
const { Worker, parentPort } = require('worker_threads');
const workers = new Set();
const maxWorkers = 4;
// Create a worker when it's not already in the pool
function createWorker() {
const worker = new Worker(__filename);
worker.on('message', message => parentPort.postMessage(message));
workers.add(worker);
// Clean up worker when it terminates
worker.on('exit', () => workers.delete(worker));
return worker;
}
// Create the worker pool
for (let i = 0; i < maxWorkers; i++) {
const worker = createWorker();
}
// Add tasks to the pool
const tasks = [
{ id: 1, work: () => console.log('Task 1') },
{ id: 2, work: () => console.log('Task 2') },
// ...
];
// Distribute tasks to the worker pool
tasks.forEach(task => {
const worker = workers.values().next().value;
worker.postMessage(task);
});In this example, we create a worker thread pool that can handle multiple tasks concurrently. The worker thread pool is created by initializing a set of worker threads and creating a function to create new workers as needed. When tasks are added to the pool, they are distributed to the available workers.