The reactor mode of libevent

Source: Internet
Author: User
Tags epoll

Through a blog post on the Lightweight network library libevent, we know that Libevent actually encapsulates/dev/poll, Kqueue, Event ports, select, poll, and Epoll event mechanisms under different operating systems, Thus providing us with a unified interface.

The libevent uses the reactor I/O design pattern, and reactor is based on the synchronous I/O mechanism, so libevent is actually a library based on the synchronous I/O mechanism.

For I/O design patterns, there are also proactor corresponding to the reactor. Let's look at the differences between the two below.

Reactor & Proactor

Reactor is based on the synchronous I/O mechanism, while Proactor is based on the asynchronous I/O mechanism. This is the biggest difference between the two.

In the blog comparing two high-performance I/O Design patterns, the author gives a very incisive explanation (not translated ...). What they have said is clear):

In general, I/O multiplexing mechanisms rely on an event demultiplexor [1, 3], an object that dispatches I/O events from a Limited number of sources to the appropriate Read/write event handlers. The developer registers interest in specific events and provides event handlers, or callbacks. The event Demultiplexor delivers the requested events to the event handlers.

The patterns that involve event demultiplexors is called Reactor and Proactor [1]. the Reactor patterns involve synchronous I/O, whereas the proactor pattern involves asynchronous I/O. in Reactor, The event Demultiplexor waits for events, indicate when a file descriptor or socket was ready for a read or write opera tion. The Demultiplexor passes this event to the appropriate handler, which was responsible for performing the actual read or WRI Te.

In the proactor pattern, by contrast, the handler-or the event Demultiplexor on behalf of the Handler-initiates Asynchrono US read and write operations.The I/O operation itself is performed by the operating system (OS). The parameters passed to the OS include the addresses of user-defined data buffers from which the OS gets data to write, O R to which the OS puts data read.the event Demultiplexor waits for events, indicate the completion of the I/O operation, and forwards those events to the appropriate handlers. For example, on Windows a handler could initiate async I/O (overlapped in Microsoft terminology) operations, and the event Demultiplexor could wait for iocompletion events [1]. The implementation of this classic asynchronous Pattern are based on an asynchronous Os-level API, and we'll call this IM Plementation the "System-level" or "true" async, because the application fully relies on the OS to execute actual I/O.

An example would help you understand the difference between Reactor and Proactor. We'll focus on the "read operation here, as the" write implementation is similar. Here's a read in Reactor:

    • An event handler declares interest in I/O events that indicate readiness for read on a particular socket
    • The event Demultiplexor waits for events
    • An event comes in and wakes-up the Demultiplexor, and the DEMULTIPLEXOR calls the appropriate handler
    • The event handler performs the actual read operation, handles the data read, declares renewed interest in I/O events, and Returns control to the dispatcher

By comparison, this is a read operation in Proactor (true async):

    • A Handler initiates A asynchronous read operation (Note:the OS must support asynchronous I/O). In this case, the handler does isn't care about I/O readiness events, but was instead registers interest in receiving complet Ion events.
    • The event Demultiplexor waits until the operation is completed
    • While the event Demultiplexor waits, the OS executes the "read operation in a parallel kernel" thread, puts data into a user -defined buffer, and notifies the event demultiplexor that the read was complete
    • The event Demultiplexor calls the appropriate handler;
    • The event handler handles the data from user defined buffer, starts a new asynchronous operation, and returns control to T He event Demultiplexor.

...

As we mentioned, the true async Proactor pattern requires operating-system-level support.

Note that the "I/O operation ..." mentioned above refers to a real I/O operation, such as reading a read buffer.

About Proactor You can also refer to another document Proactor.

  

The following excerpt from the blog libevent Source depth Analysis: Reactor mode:

The event handling mechanism of reactor

First of all, recall the normal function call mechanism: The program calls a function, function execution, program wait, function returns the result and control to the program, the program continues processing. Reactor the definition of "reactor" is an event-driven mechanism. Unlike normal function calls, where an application is not actively invoking an API to complete processing, instead of reactor the event processing flow, the application needs to provide the appropriate interface and register it on the reactor, if the corresponding event occurs, Reactor will actively invoke the interfaces registered by the application, which are also known as "callback functions". Using Libevent also registers the appropriate events and callback functions with the Libevent framework, and when these times occur, Libevent calls these callback functions to handle the corresponding events (I/O reading, timing, and signaling).

The "Hollywood Principle" to describe reactor is the right one: do not call us, we will call to inform you . For example: You go to apply for a XX company, after the interview is over. "Normal function call mechanism" Company HR comparison lazy, will not remember your contact way, how to do it, you can only after the interview to call the results of their own, have not been admitted ah, or is the basis; "Reactor" company HR wrote down your contact information, The results will be the active call to inform you: have not been admitted Ah, or rejected; you don't have to call to ask the results yourself, in fact, you do not have the HR contact information.

Advantages of the reactor model

Reactor mode is one of the prerequisites for writing high-performance Web servers, and it has the following advantages:

    • The response is fast and does not have to be blocked for a single synchronization time, although the reactor itself is still synchronous;
    • Programming is relatively simple, can avoid complex multi-threading and synchronization problems, and avoid multi-threaded/process switching overhead;
    • Scalability, can be easily by increasing the number of reactor instances to make full use of CPU resources;
    • Reusability, the reactor framework itself is independent of the specific event handling logic and has high reusability.
Reactor Mode framework

Using the reactor model, several components are required: Event source, reactor framework, multiplexing mechanism, and event handler, first look at the overall framework of the reactor model, and then describe each component one by one.

  

   1. source of the event
Linux is a file descriptor, Windows is a socket or handle, here is known as a "handle set", the program on the specified handle register the event of interest, such as I/O events.
   2. vent demultiplexer--Event Multi-channel distribution mechanism
The I/O multiplexing mechanisms provided by the operating system, such as SELECT and Epoll. The program first registers its concerned handle (the event source) and its events on the event demultiplexer, and when an event arrives, event Demultiplexer notifies "the event of one or more handles is ready in the registered handle set," And when the program receives the notification, The event can be handled in a non-blocking situation.
Corresponding to the libevent, is still select, poll, Epoll, etc., but libevent using the structure of eventop encapsulation, with a unified interface to support these I/O multiplexing mechanism, to the external hiding the underlying system mechanism.
   3. Reactor--reactor
Reactor is an event management interface that internally uses event demultiplexer to register, unregister, and run an event loop that invokes the callback function that registers the event to handle the event when an event enters the ready state. corresponding to the libevent, is the event_base structure.
A typical reactor declaration method:
1 classReactor2 {3  Public:4     intRegister_handler (Event_handler *phandler,int Event);5     intRemove_handler (Event_handler *phandler,int Event);6     voidHandle_events (Timeval *PTV);7     // ...8};
   4. Event handler--Events Handler
  The event handler provides a set of interfaces, each of which corresponds to a type of event that reactor is invoked when the corresponding event occurs and performs the corresponding event handling. Typically, it binds a valid handle. corresponds to the libevent, which is the event structure body. Here are two typical event handler class declarations, each with their pros and cons.
1 classEvent_handler2 {3  Public:4     Virtual voidHandle_read () =0;5     Virtual voidHandle_write () =0;6     Virtual voidHandle_timeout () =0;7     Virtual voidHandle_close () =0;8     VirtualHANDLE get_handle () =0;9     // ...Ten }; One classEvent_handler A { -  Public: -     //events maybe read/write/timeout/close. etc the     Virtual voidHandle_events (intevents) =0; -     VirtualHANDLE get_handle () =0; -     // ... -};
Reactor Event Processing Flow

As I said earlier, reactor the event flow "inverse", what does the event control flow look like when you use reactor mode? You can see the following sequence diagram:
  

The reactor mode of libevent

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.