Comparing Event Callbacks and Threaded Models

In the traditional threaded web model, a request comes to a webserver and is assigned to an available thread. The handling of work for that request continues on that thread until the request is complete and a response is sent.

Figure 4.1 illustrates the threaded model processing two requests, GetFile and GetData. The GetFile request opens the file, reads the contents, and then sends the data back in a response. All this occurs in order on the same thread. The GetData request connects to the database, queries the necessary data, and then sends the data in the response.

Image

Figure 4.1 Processing two requests on individual threads, using the threaded model.

Now think about how the Node.js event model does things. Instead of executing all the work for each request on individual threads, Node.js adds work to an event queue and then has a single thread running an event loop pick it up. The event loop grabs the top item in the event queue, executes it, and then grabs the next item. When executing code that is longer lived or has blocking I/O, instead of calling the function directly, it adds the function to the event queue along with a callback that will be executed after the function completes. When all events on the Node.js event queue have been executed, the Node.js application terminates.

Figure 4.2 illustrates how Node.js handles the GetFile and GetData requests. It adds the GetFile and GetData requests to the event queue. It first picks up the GetFile request, executes it, and completes by adding the Open() callback function to the event queue. Then it picks up the GetData request, executes it, and completes by adding the Connect() callback function to the event queue. This continues until there are no callback functions to be executed. Notice in Figure 4.2 that the events for each thread don’t necessarily follow a direct interleaved order. For example, the Connect request takes longer to complete than does the Read request, so Send(file) is called before Query(db).

Image

Figure 4.2 Processing two requests on a single event-driven thread, using the Node.js event model.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.36.72