【傳智播客】Libevent學習筆記(二):創建event_base


00. 目錄

聲明: 該博客來源於傳智播客C++學院相關培訓參考手冊

01. 簡介

​ 使用libevent函數之前需要分配一個或者多個event_base結構體。每個event_base結構體持有一個事件集合,可以檢測以確定哪個事件是激活的。

​ 如果設置event_base使用鎖,則可以安全地在多個線程中訪問它。然而,其事件循環只能運行在一個線程中。如果需要用多個線程檢測IO,則需要為每個線程使用一個event_base。

每個event_base都有一種用於檢測哪種事件已經就緒的“方法”,或者說后端。可以識別的方法有:

  • select
  • poll
  • epoll
  • kqueue
  • devpoll
  • evport
  • win32

​ 用戶可以用環境變量禁止某些特定的后端。比如說,要禁止kqueue后端,可以設置EVENT_NOKQUEUE環境變量。如果要用編程的方法禁止后端,請看下面關於event_config_avoid_method()的說明。

02. 創建默認的event_base

event_base_new()函數分配並且返回一個新的具有默認設置的event_base。函數會檢測環境變量,返回一個到event_base的指針。如果發生錯誤,則返回NULL。選擇各種方法時,函數會選擇操作系統支持的最快方法。

函數相關說明:

/**
 * Create and return a new event_base to use with the rest of Libevent.
 *
 * @return a new event_base on success, or NULL on failure.
 *
 * @see event_base_free(), event_base_new_with_config()
 */

struct event_base *event_base_new(void);
功能: 
	創建一個默認屬性的struct event_base對象
參數:
	無
返回值:
	成功: 返回struct event_base結構體指針
	失敗: NULL

event_base_new()函數聲明在<event2/event.h>中,首次出現在libevent 1.4.3版。

大多數情況下, 我們創建默認的event_base就可以滿足我們的需求。

03. 創建復雜的event_base

要對取得什么類型的event_base有更多的控制,就需要使用event_config

event_config是一個容納event_base配置信息的不透明結構體。需要event_base時,將event_config傳遞給event_base_new_with_config()

相關頭文件: libevent-2.0.22-stable/include/event2/event.h

3.1 event_config_new函數

/**
   Allocates a new event configuration object.

   The event configuration object can be used to change the behavior of
   an event base.

   @return an event_config object that can be used to store configuration, or
     NULL if an error is encountered.
   @see event_base_new_with_config(), event_config_free(), event_config
*/
struct event_config *event_config_new(void);
功能:
	分配一個event_config
參數:
	無
返回值:
	成功:返回struct event_config結構體指針
	失敗:NULL

3.2 event_base_new_with_config函數

/**
  Initialize the event API.

  Use event_base_new_with_config() to initialize a new event base, taking
  the specified configuration under consideration.  The configuration object
  can currently be used to avoid certain event notification mechanisms.

  @param cfg the event configuration object
  @return an initialized event_base that can be used to registering events,
     or NULL if no event base can be created with the requested event_config.
  @see event_base_new(), event_base_free(), event_init(), event_assign()
*/
struct event_base *event_base_new_with_config(const struct event_config * cfg);
功能:
	初始化一個新的event_base
參數:
	cfg event_config結構體指針 
返回值:
	成功:返回一個可以用於注冊事件的初始化好的event_base對象
    失敗:NULL

3.3 event_config_free函數

/**
   Deallocates all memory associated with an event configuration object

   @param cfg the event configuration object to be freed.
*/
void event_config_free(struct event_config *cfg);
功能:
	釋放event_config對象
參數:
	cfg event_config_new函數的返回值
返回值:
	無

3.4 event_config_avoid_method函數

/**
   Enters an event method that should be avoided into the configuration.

   This can be used to avoid event mechanisms that do not support certain
   file descriptor types, or for debugging to avoid certain event
   mechanisms.  An application can make use of multiple event bases to
   accommodate incompatible file descriptor types.

   @param cfg the event configuration object
   @param method the name of the event method to avoid
   @return 0 on success, -1 on failure.
*/
int event_config_avoid_method(struct event_config *cfg, const char *method);
功能:
	可以通過名字讓libevent避免使用特定的可用后端。
參數:
	cfg event_config對象指針
	method 避免使用特定的后端
	
返回值:
	成功 0
    失敗 -1

3.5 event_config_require_features函數

/**
   Enters a required event method feature that the application demands.

   Note that not every feature or combination of features is supported
   on every platform.  Code that requests features should be prepared
   to handle the case where event_base_new_with_config() returns NULL, as in:
   <pre>
     event_config_require_features(cfg, EV_FEATURE_ET);
     base = event_base_new_with_config(cfg);
     if (base == NULL) {
       // We can't get edge-triggered behavior here.
       event_config_require_features(cfg, 0);
       base = event_base_new_with_config(cfg);
     }
   </pre>

   @param cfg the event configuration object
   @param feature a bitfield of one or more event_method_feature values.
          Replaces values from previous calls to this function.
   @return 0 on success, -1 on failure.
   @see event_method_feature, event_base_new_with_config()
*/
int event_config_require_features(struct event_config *cfg, int feature);
功能:
	設置libevent不使用不能提供所有指定特征的后端。
參數:
	cfg event_config結構體指針
	feature 指定特征的后端
返回值:
	成功 0
    失敗 -1

指定特征的后端

/**
   A flag used to describe which features an event_base (must) provide.

   Because of OS limitations, not every Libevent backend supports every
   possible feature.  You can use this type with
   event_config_require_features() to tell Libevent to only proceed if your
   event_base implements a given feature, and you can receive this type from
   event_base_get_features() to see which features are available.
*/
enum event_method_feature {
    /** Require an event method that allows edge-triggered events with EV_ET. */
    EV_FEATURE_ET = 0x01,
    /** Require an event method where having one event triggered among
     * many is [approximately] an O(1) operation. This excludes (for
     * example) select and poll, which are approximately O(N) for N
     * equal to the total number of possible events. */
    EV_FEATURE_O1 = 0x02,
    /** Require an event method that allows file descriptors as well as
     * sockets. */
    EV_FEATURE_FDS = 0x04
};

event_config_require_features()可識別的特征值有:

  • EV_FEATURE_ET:要求支持邊沿觸發的后端。

  • EV_FEATURE_O1:要求添加、刪除單個事件,或者確定哪個事件激活的操作是O(1)復雜度的后端。

  • EV_FEATURE_FDS:要求支持任意文件描述符,而不僅僅是套接字的后端。

3.6 event_config_set_flag函數

/**
 * Sets one or more flags to configure what parts of the eventual event_base
 * will be initialized, and how they'll work.
 *
 * @see event_base_config_flags, event_base_new_with_config()
 **/
int event_config_set_flag(struct event_config *cfg, int flag);
功能:
	設置讓libevent在創建event_base時設置一個或者多個將在下面介紹的運行時標志。
參數:
	cfg event_config結構體指針
	flag 指定的標志
返回值:
	成功 0
    失敗 -1

對應的標志有

/**
   A flag passed to event_config_set_flag().

    These flags change the behavior of an allocated event_base.

    @see event_config_set_flag(), event_base_new_with_config(),
       event_method_feature
 */
enum event_base_config_flag {
    /** Do not allocate a lock for the event base, even if we have
        locking set up. */
    EVENT_BASE_FLAG_NOLOCK = 0x01,
    /** Do not check the EVENT_* environment variables when configuring
        an event_base  */
    EVENT_BASE_FLAG_IGNORE_ENV = 0x02,
    /** Windows only: enable the IOCP dispatcher at startup

        If this flag is set then bufferevent_socket_new() and
        evconn_listener_new() will use IOCP-backed implementations
        instead of the usual select-based one on Windows.
     */
    EVENT_BASE_FLAG_STARTUP_IOCP = 0x04,
    /** Instead of checking the current time every time the event loop is
        ready to run timeout callbacks, check after each timeout callback.
     */
    EVENT_BASE_FLAG_NO_CACHE_TIME = 0x08,

    /** If we are using the epoll backend, this flag says that it is
        safe to use Libevent's internal change-list code to batch up
        adds and deletes in order to try to do as few syscalls as
        possible.  Setting this flag can make your code run faster, but
        it may trigger a Linux bug: it is not safe to use this flag
        if you have any fds cloned by dup() or its variants.  Doing so
        will produce strange and hard-to-diagnose bugs.

        This flag can also be activated by settnig the
        EVENT_EPOLL_USE_CHANGELIST environment variable.

        This flag has no effect if you wind up using a backend other than
        epoll.
     */
    EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST = 0x10
};

event_config_set_flag()可識別的選項值有:

  • EVENT_BASE_FLAG_NOLOCK:不要為event_base分配鎖。設置這個選項可以為event_base節省一點用於鎖定和解鎖的時間,但是讓在多個線程中訪問event_base成為不安全的。

  • EVENT_BASE_FLAG_IGNORE_ENV:選擇使用的后端時,不要檢測EVENT_*環境變量。使用這個標志需要三思:這會讓用戶更難調試你的程序與libevent的交互。

  • EVENT_BASE_FLAG_STARTUP_IOCP:僅用於Windows,讓libevent在啟動時就啟用任何必需的IOCP分發邏輯,而不是按需啟用。

  • EVENT_BASE_FLAG_NO_CACHE_TIME:不是在事件循環每次准備執行超時回調時檢測當前時間,而是在每次超時回調后進行檢測。注意:這會消耗更多的CPU時間。

  • EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST:告訴libevent,如果決定使用epoll后端,可以安全地使用更快的基於changelist的后端。epoll-changelist后端可以在后端的分發函數調用之間,同樣的fd多次修改其狀態的情況下,避免不必要的系統調用。但是如果傳遞任何使用dup()或者其變體克隆的fd給libevent,epoll-changelist后端會觸發一個內核bug,導致不正確的結果。在不使用epoll后端的情況下,這個標志是沒有效果的。也可以通過設置EVENT_EPOLL_USE_CHANGELIST環境變量來打開epoll-changelist選項。

注意:

設置event_config,請求OS不能提供的后端是很容易的。比如說,對於libevent 2.0.1-alpha,在Windows中是沒有O(1)后端的;在Linux中也沒有同時提供EV_FEATURE_FDS和EV_FEATURE_O1特征的后端。如果創建了libevent不能滿足的配置,event_base_new_with_config()會返回NULL。

3.7 event_config_set_num_cpus_hint函數

函數當前僅在Windows上使用IOCP時有用,雖然將來可能在其他平台上有用。這個函數告訴event_config在生成多線程event_base的時候,應該試圖使用給定數目的CPU。注意這僅僅是一個提示:event_base使用的CPU可能比你選擇的要少。

/**
 * Records a hint for the number of CPUs in the system. This is used for
 * tuning thread pools, etc, for optimal performance.  In Libevent 2.0,
 * it is only on Windows, and only when IOCP is in use.
 *
 * @param cfg the event configuration object
 * @param cpus the number of cpus
 * @return 0 on success, -1 on failure.
 */
int event_config_set_num_cpus_hint(struct event_config *cfg, int cpus);
功能:
	設置試圖給定數目的CPU。
參數:
	cfg event_config結構體指針
	cpus CPU數量
返回值:
	成功 0
    失敗 -1

官方參考示例:

struct event_config *cfg;
struct event_base *base;
int i;
 
/* My program wants to use edge-triggered events if at all possible.  So
   I'll try to get a base twice: Once insisting on edge-triggered IO, and
   once not. */
for (i=0; i<2; ++i) {
    cfg = event_config_new();
 
    /* I don't like select. */
    event_config_avoid_method(cfg, "select");
 
    if (i == 0)
        event_config_require_features(cfg, EV_FEATURE_ET);
 
    base = event_base_new_with_config(cfg);
    event_config_free(cfg);
    if (base)
        break;
    /* If we get here, event_base_new_with_config() returned NULL.  If
       this is the first time around the loop, we'll try again without
       setting EV_FEATURE_ET.  If this is the second time around the
       loop, we'll give up. */
}

總述:

以上函數和類型在<event2/event.h>中聲明。

EVENT_BASE_FLAG_IGNORE_ENV標志首次出現在2.0.2-alpha版本。event_config_set_num_cpus_hint()函數是2.0.7-rc版本新引入的。本節的其他內容首次出現在2.0.1-alpha版本。

04. 檢查event_base的后端

有時候需要檢查event_base支持哪些特征,或者當前使用哪種方法。

4.1 event_get_supported_methods函數

/**
   Gets all event notification mechanisms supported by Libevent.

   This functions returns the event mechanism in order preferred by
   Libevent.  Note that this list will include all backends that
   Libevent has compiled-in support for, and will not necessarily check
   your OS to see whether it has the required resources.

   @return an array with pointers to the names of support methods.
     The end of the array is indicated by a NULL pointer.  If an
     error is encountered NULL is returned.
*/
const char **event_get_supported_methods(void);
功能:
	獲取當前系統支持的后端。
參數:
	無
返回值:
	成功 返回一個指針,指向libevent支持的方法名字數組
    失敗 NULL

參考程序:

#include <stdio.h>
#include <event.h>

int main(void)
{
    int i = 0;


    const char **pstr = event_get_supported_methods();
    if (NULL == pstr)
    {   
        printf("event_get_supported_methods failed...\n"); 
        return 1;
    }   

    printf("Libevent version: %s\n", event_get_version());
    for (i = 0; NULL != pstr[i]; i++) 
    {   
        printf("\t%s\n", pstr[i]); 
    }   

    return 0;
}

執行結果:

注意:

這個函數返回libevent被編譯以支持的方法列表。然而libevent運行的時候,操作系統可能不能支持所有方法。比如說,可能OS X版本中的kqueuebug太多,無法使用。

4.2 event_base_get_method函數

/**
 Get the kernel event notification mechanism used by Libevent.

 @param eb the event_base structure returned by event_base_new()
 @return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
 */
const char *event_base_get_method(const struct event_base *base);
功能:
	獲取當前base使用的后端。
參數:
	base event_base對象
返回值:
	成功 返回一個指針,指向使用的后端。
    失敗 NULL。

參考示例:

#include <stdio.h>
#include <event.h>

int main(void)
{
    struct event_base *base = NULL;
    //創建一個對象
    base = event_base_new();
    if (NULL == base)
    {   
        printf("event_base_new failded...\n");
        return 1;
    }   

    printf("methods: %s\n", event_base_get_method(base));

    //釋放對象
    event_base_free(base);

    return 0;
}

執行結果:

4.3 event_base_get_features函數

/**
   Return a bitmask of the features implemented by an event base.  This
   will be a bitwise OR of one or more of the values of
   event_method_feature

   @see event_method_feature
 */
int event_base_get_features(const struct event_base *base);
功能:
	返回event_base支持的特征的比特掩碼。
參數:
	base event_base對象
返回值:
	成功 特征的比特掩碼。
    失敗 0。

參考代碼:

#include <stdio.h>
#include <event.h>

int main(void)
{
    struct event_base *base = NULL;

    enum event_method_feature f;

    base = event_base_new();
    if (NULL == base)
    {
        printf("event_base_new failded...\n");
        return 1;
    }

    f = event_base_get_features(base);
    if ((f & EV_FEATURE_ET))
        printf("  Edge-triggered events are supported.");
    if ((f & EV_FEATURE_O1))
        printf("  O(1) event notification is supported.");
    if ((f & EV_FEATURE_FDS))
        printf("  All FD types are supported.");
    printf("\n");
    event_base_free(base);

    return 0;
}

執行結果:

05. 釋放event_base

使用完event_base之后,使用event_base_free()進行釋放。

/**
  Deallocate all memory associated with an event_base, and free the base.

  Note that this function will not close any fds or free any memory passed
  to event_new as the argument to callback.

  @param eb an event_base to be freed
 */
void event_base_free(struct event_base *base);
功能:
	釋放base
參數:
	base event_base對象
返回值:
	無

參考代碼:

#include <stdio.h>
#include <event.h>

int main(void)
{
    struct event_base *base = NULL;

	//創建base對象
    base = event_base_new();
    if (NULL == base)
    {   
        printf("event_base_new failded...\n");
        return 1;
    }   
    
	//釋放base
    event_base_free(base);

    return 0;
}

注意:

這個函數不會釋放當前與event_base關聯的任何事件,或者關閉他們的套接字,或者釋放任何指針。

event_base_free()定義在<event2/event.h>中,首次由libevent 1.2實現。

06. 設置event_base的優先級

​ libevent支持為事件設置多個優先級。然而,event_base默認只支持單個優先級。可以調用event_base_priority_init()設置event_base*的優先級數目。

event_base_priority_init函數


/**
  Set the number of different event priorities

  By default Libevent schedules all active events with the same priority.
  However, some time it is desirable to process some events with a higher
  priority than others.  For that reason, Libevent supports strict priority
  queues.  Active events with a lower priority are always processed before
  events with a higher priority.

  The number of different priorities can be set initially with the
  event_base_priority_init() function.  This function should be called
  before the first call to event_base_dispatch().  The
  event_priority_set() function can be used to assign a priority to an
  event.  By default, Libevent assigns the middle priority to all events
  unless their priority is explicitly set.

  Note that urgent-priority events can starve less-urgent events: after
  running all urgent-priority callbacks, Libevent checks for more urgent
  events again, before running less-urgent events.  Less-urgent events
  will not have their callbacks run until there are no events more urgent
  than them that want to be active.

  @param eb the event_base structure returned by event_base_new()
  @param npriorities the maximum number of priorities
  @return 0 if successful, or -1 if an error occurred
  @see event_priority_set()
 */
int event_base_priority_init(struct event_base *base, int pri);
功能:
	設置base優先級
參數:
	base event_base對象
	pri 這個數目至少是1。每個新的事件可用的優先級將從0(最高)pri-1(最低)。
返回值:
	成功 0
	失敗 -1
        
/** Largest number of priorities that Libevent can support. */
#define EVENT_MAX_PRIORITIES 256
常量EVENT_MAX_PRIORITIES表示pri的上限。調用這個函數時為pri給出更大的值是錯誤的。

注意:

必須在任何事件激活之前調用這個函數,最好在創建event_base后立刻調用。

關於示例,請看event_priority_set的文檔。

默認情況下,與event_base相關聯的事件將被初始化為具有優先級pri/ 2。event_base_priority_init()函數定義在<event2/event.h>中,從libevent 1.0版就可用了。

07. fork之后重新初始化base

不是所有事件后端都在調用fork()之后可以正確工作。所以,如果在使用fork()或者其他相關系統調用啟動新進程之后,希望在新進程中繼續使用event_base,就需要進行重新初始化。

event_reinit函數

/**
  Reinitialize the event base after a fork

  Some event mechanisms do not survive across fork.   The event base needs
  to be reinitialized with the event_reinit() function.

  @param base the event base that needs to be re-initialized
  @return 0 if successful, or -1 if some events could not be re-added.
  @see event_base_new()
*/
int event_reinit(struct event_base *base);
功能:
	重新初始化base
參數:
	base event_base對象
返回值:
	成功 0
	失敗 -1

官方參考示例

struct event_base *base = event_base_new();
 
/* ... add some events to the event_base ... */
 
if (fork()) {
    /* In parent */
    continue_running_parent(base); /*...*/
} else {
    /* In child */
    event_reinit(base);
    continue_running_child(base); /*...*/
}

event_reinit()定義在<event2/event.h>中,在libevent 1.4.3-alpha版中首次可用。

08. 參考

相關書籍: http://www.wangafu.net/~nickm/libevent-book/Ref2_eventbase.html

官方參考網站: https://www.monkey.org/~provos/libevent/doxygen-2.0.1/index.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM