我们可能考虑到主线程正在阻塞dispatch上,由于没有任何事件就绪,因此dispatch会阻塞到设置的超时时间才会返回;为了能让dispatch在需要返回的时候立刻返回,Libevent采用了和信号处理相同的方式:定义一个内部事件专门用来唤醒主线程,其实就是添加这个内部事件,然后唤醒的方式就是往内部事件监听的管道上写数据。
1. event_base中的数据
与事件event一样,event_base中也会存在这样一个内部事件用来进行唤醒,以及一些其他的数据成员,如下所示:
struct event_base {
......
/* Notify main thread to wake up break, etc. */
/** True if the base already has a pending notify, and we don't need
* to add any more. */
int is_notify_pending;//如果为1表示当前可以唤醒主线程,否则不能唤醒主线程
/** A socketpair used by some th_notify functions to wake up the main
* thread. */
evutil_socket_t th_notify_fd[2];//一端读、一端写,用来触发唤醒事件
/** An event used by some th_notify functions to wake up the main
* thread. */
struct event th_notify;//唤醒event,被添加到监听集合中的对象
/** A function used to wake up the main thread from another thread. */
int (*th_notify_fn)(struct event_base *base);//执行唤醒操作的函数(不是唤醒event的回调函数)
}
这个is_notify_pending是为了避免同时多个线程在同一时间内都去唤醒主线程。
2. 创建唤醒event
唤醒event是一个内部事件,用户自己是无法去创建、添加这样一个事件的。Libevent中,内部事件的创建和添加都是通过内部函数来进行的。当创建一个event_base的时候,在event_base_new_with_config函数中就会创建这样一个内部事件:
struct event_base *
event_base_new_with_config(const struct event_config *cfg)
{
......
#ifndef _EVENT_DISABLE_THREAD_SUPPORT //如果支持多线程,就给base分配锁和条件变量
if (EVTHREAD_LOCKING_ENABLED() && //如果启用了线程锁,并且没有设置cfg或者flags中没有设置无锁
(!cfg || !(cfg->flags & EVENT_BASE_FLAG_NOLOCK))) {
int r;
......
r = evthread_make_base_notifiable(base);//为base的th_notify_fd注册了一对文件描述符,一个用于读,一个用于写,用于读的文件描述符与th_notify事件绑定并添加监听