# Node.js multithreading: Worker threads and why they matter - LogRocket Blog

source: https://ift.tt/JRySq7t tags: #literature #programming #software-engineering #airtable #javascript uid: 202301260141

The need for threads to perform CPU-intensive tasks What happens if we need to do synchronous-intense stuff, such as making complex calculations in memory in a large dataset? Then we might have a synchronous block of code that takes a lot of time and will block the rest of the code.

Imagine that a calculation takes 10 seconds. If we are running a web server, that means that all of the other requests get blocked for at least 10s because of that calculation. That’s a disaster; anything more than 100ms could be too much.

JavaScript and Node.js were not meant to be used for CPU-bound tasks. Since JavaScript is single-threaded, this will freeze the UI in the browser and queue any I/O events in Node.js.

The naive solution: Synchronous code-splitting Node.js won’t evaluate the next code block in the event queue until the previous one has finished executing. So, one simple thing we can do is split our code into smaller synchronous code blocks and call setImmediate(callback) to tell Node.js we are done. This way, it can continue executing things that are pending in the queue; or, in other words, it can move on to the next iteration (or tick”) of the event loop.

This is a pretty good hack for splitting up synchronous work in Javascript. Good to be aware of #programming #insights

The reality is that we can already do background processing in Node.js: we can fork the process and do exactly that using message passing, which you can imagine as simply as passing a message from one process to another. This achieves the following goals:

The main process can communicate with the child process by sending and receiving events No memory is shared All the data exchanged is cloned,” meaning that changing it in one side doesn’t change it on the other side If we don’t share memory, we don’t have race conditions, and we don’t need threads! Well, hold on. This is a solution, but it’s not the ideal solution. Forking a process is expensive and slow — it means running a new virtual machine from scratch and using a lot of memory, since processes don’t share memory.

What are Worker threads? Worker threads have isolated contexts. They exchange information with the main process using message passing, so we avoid the race conditions problem regular threads have! But they do live in the same process, so they use a lot less memory.


Date
February 22, 2023