In-depth analysis of libevent source code 9

Source: Internet
Author: User
In-depth analysis of libevent source code 9

-- Integrated timer event

Zhang Liang

Now let's analyze in detail the integration of I/O events and timer events in libevent. Compared with signal, the integration of timer events is much more intuitive and simple. Libevent has made some optimizations to the heap adjustment operation. This section also describes these optimization methods.

1. integrate into the event Main Loop

Because the system's I/O mechanism, such as select () and epoll_wait (), allows the program to set a maximum wait time (also known as the maximum timeout time) Timeout, even if no I/O event occurs, they also ensure that they can be returned within the timeout time.

Set the timeout time of system I/O based on the minimum timeout time of all timer events. When system I/O returns, activate all ready timer events, in this way, Timer events can be perfectly integrated into the system's I/O mechanism.

The specific code is in the event_base_loop () of the source file event. C. Now let's compare the code to see the solution:
If (! Base-> event_count_active &&! (Flags & evloop_nonblock) {<br/> // calculate the maximum wait time for the evsel-> dispatch Based on the timer event <br/> timeout_next (base, & TV _p ); <br/>} else {<br/> // if there are any activity events, do not wait. Let evsel-> dispatch return immediately <br/> evutil_timerclear (& TV ); <br/>}< br/> //... <br/> // call select () or epoll_wait () to wait for the ready I/O event <br/> res = evsel-> dispatch (base, evbase, TV _p ); <br/> //... <br/> // process the timeout event and insert it into the active linked list. <br/> timeout_process (base );

The timeout_next () function calculates the wait time based on the event with the minimum timeout value in the heap and the current time. Let's look at the code below:
Static int timeout_next (struct event_base * base, struct timeval ** TV _p) <br/>{< br/> struct timeval now; <br/> struct event * EV; <br/> struct timeval * TV = * TV _p; <br/> // the first element of the heap has the minimum timeout value <br/> If (EV = min_heap_top (& base-> timeheap) = NULL) {<br/> // if no scheduled event exists, set the wait time to null, which indicates that it is blocked until an I/O event occurs. <br/> * TV _p = NULL; <br/> return (0); <br/>}< br/> // obtain the current time <br/> gettime (base, & now ); <br/> // if the time-out period is <= the current value and cannot be waited, return immediately <br/> If (evutil_timercmp (& ev-> ev_timeout, & now, <=) {<br/> evutil_timerclear (TV); <br/> return (0 ); <br/>}< br/> // calculation wait time = Current Time-Minimum timeout <br/> evutil_timersub (& ev-> ev_timeout, & now, TV ); <br/> return (0); <br/>}

2 Timer


Libevent uses heap to manage timer events. Its key value is the event timeout time. The source code is located in the min_heap.h file.

All data structures have a detailed introduction to the heap. the time complexity of inserting and deleting elements to the heap is O (lgn), and N is the number of elements in the heap, the complexity of obtaining the minimum key value (small root heap) is O (1 ). Heap is a Complete Binary Tree, and the basic storage method is an array.

The libevent implementation heap is still relatively lightweight, although I don't like this encoding method (for some complicated expressions ). Here, we will take the insert element as an example to compare and describe the size in the pseudocode below, which indicates the number of elements in the current heap:

The typical code logic is as follows:
Heap [size ++] = new; // put it at the end of the array, and the number of elements + 1 <br/> // The following is the code logic of shift_up, constantly adjust the new value <br/> _ child = size; <br/> while (_ child> 0) // loop <br/>{< br/> _ parent = (_ child-1)/2; // calculate the parent <br/> If (heap [_ parent]. key <peap [_ child]. key) <br/> break; // adjustment ends and the cycle is exceeded <br/> swap (_ parent, _ child); // switch Parent and Child <br/>}

The heap code of libevent optimizes this process. When a new element is inserted, it only reserves a location for the new element (hole is located at the end of the array at the beginning ), but it does not immediately Insert the new element into the hole, but constantly adjusts the hole value to the parent node, and finally confirms that the hole is the location of the new element, the new elements are inserted to the hole. Therefore, the assignment operation is less than the previous code in the adjustment process. The Code logic is as follows:

The following is the code logic of shift_up (), which constantly adjusts the new "Reserved position"
 
// The following is the shift_up () code logic, constantly adjusting the new "Reserved position" Up <br/> _ hole = size; // _ hole is the reserved position for new, but the new is not immediately placed <br/> while (_ hole> 0) // loop <br/>{< br/> _ parent = (_ hole-1)/2; // calculate the parent <br/> If (heap [_ parent]. key <New. key) <br/> break; // The adjustment ends and the heap jumps out of the loop. <br/> heap [_ hole] = heap [_ parent]; // adjust the parent downward <br/> _ hole = _ parent; // adjust _ hole to _ parent <br/>}< br/> heap [_ hole] = new; // The adjustment ends, insert new to the position indicated by _ hole <br/> size ++; // number of elements + 1

Since each adjustment requires less than one value assignment operation, the adjustment efficiency will be improved when the adjustment path is relatively long. The min_heap_shift_up _ () function in libevent is the specific implementation of the above logic. The corresponding downward adjustment function is min_heap_shift_down _().

For example, insert new element 2 to a small root heap 3, 5, 8, 7, 12, and use the typical code logic in the first middle. The adjustment process is shown in:

 

Use the heap adjustment logic in libevent. The adjustment process is shown in:

 

The deletion and element modification operations follow the same logic, so they are no longer arrogant.

Section 3

By setting the wait time of the system I/O mechanism, Timer events can be easily integrated. This article mainly analyzes the optimization of libevent on heap adjustment operations.

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.