Worker Threads
Definition
A built-in module that enables the creation of true multi-threaded Node.js applications. Unlike clusters (which create entirely new processes), worker threads share memory and are much lighter.
Explain Like I'm New
If Clustering is cloning the entire restaurant (new building, new manager, new kitchen), Worker Threads are just hiring extra chefs for the existing kitchen. Because they are in the same kitchen, the chefs can share the same ingredients (shared memory) without having to mail them to each other.
Real World Example
An app that resizes uploaded images. Image resizing requires heavy math (CPU intensive). If the main Event Loop does the math, the server freezes for everyone else. Instead, the main loop tosses the image to a background Worker Thread. The background thread does the math, and returns the result when it's done.
Common Use Cases
- •CPU-intensive calculations (Image processing, video encoding, cryptography)
- •Preventing Event Loop blockage
Interactive Example
Interview Questions
basic
- Are Worker Threads used for speeding up Database queries (I/O)?
intermediate
- How do Worker Threads communicate with the main thread?