Running CPU-Bound Tasks

Get familiar with CPU-bound synchronous tasks and learn how to use CPU-bound algorithms to solve this issue.

The totalSales() API that we implemented previously was (intentionally) expensive in terms of resources and took a few hundred milliseconds to run. Nonetheless, invoking the totalSales() function didn’t affect the ability of the application to process concurrent incoming requests. Invoking an asynchronous operation always causes the stack to unwind back to the event loop, leaving it free to handle other requests.

But what happens when we run a synchronous task that takes a long time to complete and that never gives the control back to the event loop until it has finished? This kind of task is also known as a CPU-bound task because its main characteristic is that it’s heavy on CPU utilization rather than being heavy on I/O operations.

Let’s immediately work on an example to see how these types of tasks behave in Node.js.

Solving the subset sum problem

Let’s now choose a computationally expensive problem to use as a base for our experiment. A good candidate is the subset sum problem, which decides whether a set (or ...

Get hands-on with 1400+ tech skills courses.