The implementaiton of event loop with Libuv or Libevent on v8, why is it necessary?

Viewed 343

A Javascript web application has an event loop to handle the call stack and it loops around to check for any task queues returned by the browser's web API to run when the call stack is free. I will use v8 as the example for the javascript engine.

I've always pictured this call-stack as part of the V8 engine, it ultimately executes our Javascript as a synchronous program. Any delegation of multi-threaded action to an API like libuv/libevent must return back to the V8 execution call stack by asynchronous processing.

But recently, I've read chromium and node.js uses the event loop provided from libevent/libuv over the v8 implementation. This part really messes with my mental model a bit. The event loop is the perfect solution to get asynchronous processing when it resides in v8, we wait for API to return a queue to our macro/microtask and execute them by the next loop around priority check.

why do we need to take it out of v8 (as the most diagram shows event loop resides outside of v8)? if the event loop is outside of v8, does that mean v8 is no longer executing the javascript code anymore but instead the outside event loop executing our Javascript program and other codes provided by the respective libraries?

1 Answers

Frankly this is also my first time knowing that event loop component is not part of v8.

But I don’t have issue understanding that we can take it out of v8. I know I’m not authoritative but here’s me sharing my understanding with you:

Your previous mind model goes like, v8 actively busy loops to check over signal of continuation.

In the new model, that responsibility is just shift over to libuv, v8 registers a callback to libuv, saying that “I’m waiting for signal of a certain file/network/timeout IO interrupt, call me back when it happens”, and then v8 goes to sleep, leaving libuv busy looping.

When that signal arrives, libuv callbacks to v8 to wake it up, and v8 continues to execute JS tasks. So not, libuv doesn’t execute JavaScript, it’s still v8.

The only thing changed is where to put the looping code. This is just a matter of where to draw the boundary between software components.

Related