Difference between the Event Loop and threads

Sergii Riabokon
2 min readAug 26, 2023

--

NodeJS is originally implemented having only one thread of execution. Every file reading, networking operations in Node is available as a synchronous or as an asynchronous execution. Synchronous execution blocks the current thread until operation exits with a result. In contrast, asynchronous operations does not block the main thread of execution, but are triggered later in a so called event-loop handler.

For example I/O functions readFileSync() and readFile(), writeFileSync() and writeFile().

Event-loops starts right after executing current file outer-scope statements. It contains following phases:

1. Timer. Callbacks from setTimeout and setInterval functions.

2. Idle. Internal callbacks for nodejs garbage collector tasks.

3. Pending callbacks from previous asynchronous handlers.

4. Poll. handlers from a completed I/O operations with filesystem, network.

5. Check. Specific callbacks from setImmediate functions calls.

6. Close callbacks. When closing a network socket requires additional code to run, it runs the one during this phase.

The event loop runs in a cycle until the execution of requested deferred operations results with an error or a success.

Event-loop is supported on the Operating-System level.

Latest NodeJs (from version 10) allows to run a worker thread, that runs OS threads to perform concurrent code blocks.

The main difference between the two is how hardware CPU processes event-loop and threads code.

Calculation-heavy code with multiple threads is being executed by multiple CPU cores (if they are available). In contrast event-loop code always utilises only one CPU core. In that case difficult computation should be performed by threads, not the event loop. Originally NodeJS was not a good option for making difficult mathematical computations. Moreover there are technologies like CUDA, that utilises the graphical processor unit for speeding-up concurrent mathematical operations.

--

--

Sergii Riabokon
Sergii Riabokon

Written by Sergii Riabokon

Technical blog about programming and related stuff. Mostly contains my personal discoveries and some memorable notes.

No responses yet