Search code examples
node.jsevent-handlingvert.xsingle-threaded

Event loop based applications on single CPU machines


As I understand, event loop based applications have a thread that is always running. I am curious to understand the behaviour these will have on a single CPU machine.

Edit : This is not specifically targeted at node.js applications. I have seen application written in Java that implement an event loop have a thread running in an infinite loop.


Solution

  • This is not correct. The event-based thread in something like node.js runs only when there is actually some event to serve and some event handler to run for that event. Most of the time, the thread is idle just waiting for the next event to trigger it to run again and not using CPU cycles while idle. So, it uses no more CPU than the amount of time that code is actually executing.

    Depending upon the system, there may also be some housekeeping tasks that also occasionally use some CPU (like garbage collection), but these will also do their job and then be idle again.

    Also, relevant to the discussion is that node.js runs all your Javascript in a single thread, but it may also use other threads for the implementation of various library functions (such as file I/O). In fact, it has an internal thread pool that is used by parts of the library.