0

Revised Question

I would like to know how the event loop of nodejs (whatever underlying implementation it is, may it be v8, libuv, libev) loops without exhausting the CPU. As the code example below shows, a sleep call is inserted in order to "free" the CPU and prevent the while loop using up the CPU. Since someone has already pointed out that it is not the case, then I would like to know what mechanism is employed in nodejs (or its underlying libraries) for such purpose?

Linking to relative sections of the source code is welcome. Thanks.

Original Question

I am asking about the nodejs internals: I would like to know if there is any sleep time between the ticks in nodejs' event loop.

In other words, I assume nodejs internals look like the code below, I would like to know what is the value of sometime, if any.

while(true) {
  for(event in queue) handleEvent(event);
  sleep(sometime);
}

I made such assumption because I believe there must exist some kind of sleeping such that the while loop will not exhaust the CPU.

KevinResoL
  • 982
  • 8
  • 19
  • The stack unwinds with `.nextTick()`, but there is no requirement that nodejs does a sleep at all so you are starting with a false assumption. And, your pseudo code for how you think the event loop works is likely to correct either. The V8 Javascript engine is open source. You could go look at how it actually works if you really needed to know. – jfriend00 Apr 02 '17 at 06:35
  • But, we'd probably all have better luck helping you with whatever your real problem is (e.g. why do you think you want to know this?). – jfriend00 Apr 02 '17 at 06:37
  • Question revised, please have a look. Thanks~ – KevinResoL Apr 02 '17 at 10:20
  • 1
    You'd have to find the actual relevant part of the nodejs code to know for sure, but it's certainly possible to use signalling (like mutexes). It can run a while loop until the event queue is empty, then waits on a mutex. Then, when any other thread (such as a disk I/O thread) puts anything in the queue such as a completion callback in the event queue, it triggers that mutex which causes it to wake up and serve the event. This is how any multi-threaded queuing system would work. – jfriend00 Apr 02 '17 at 16:35
  • A couple references for you: [libuv event loop design overview](http://docs.libuv.org/en/v1.x/design.html#the-i-o-loop) and [Basics of libuv](https://nikhilm.github.io/uvbook/basics.html). – jfriend00 Apr 02 '17 at 16:44

1 Answers1

0

No there is no sleep, because that would be blocking. This answer has a lot of details about the Node.js internals that are relevant to your question.

Jason Livesay
  • 6,317
  • 3
  • 25
  • 31