一般来说,是主线程执行event_base_dispatch函数。本文也是如此,如无特别说明,event_base_dispatch函数是由主线程执行的。
notify的理由:
本文要说明的问题是,当主线程在执行event_base_dispatch进入多路IO复用函数时,会处于休眠状态,休眠前解锁。此时,其他线程可能想往event_base添加一个event,这个event可能是一般的IO event也可能是超时event。无论哪个,都需要及时告知主线程:有新的event要加进来。要实现这种功能就需要Libevent提供一种机制来提供唤醒主线程。
工作原理:
Libevent提供的唤醒主线程机制也是挺简单的,其原理和《信号event的处理》一文中提到的方法是一样的。提供一个内部的IO event,专门用于唤醒主线程。当其他线程有event要add进来时,就往这个内部的IO event写入一个字节。此时,主线程在dispatch时,就能检测到可读,也就醒来了。这就完成了通知。这过程和Libevent处理信号event是一样的。
相关结构体:
下面看一下Libevent的实现代码。同信号处理一样,先来看一下event_base提供了什么成员。
- struct event_base {
- …
- //event_base是否处于通知的未决状态。即次线程已经通知了,但主线程还没处理这个通知
- int is_notify_pending;
- evutil_socket_t th_notify_fd[2]; //通信管道
- struct event th_notify;//用于监听th_notify_fd的读端
- //有两个可供选择的通知函数,指向其中一个通知函数
- int (*th_notify_fn)(struct event_base *base);
- };
创建通知event并将之加入到event_base:
现在看Libevent怎么创建通信通道,以及怎么和event相关联。在event_base_new_with_config(event_base_new会调用该函数)里面会调用evthread_make_base_notifiable函数,使得libevent变成可通知的。只有在已经支持多线程的情况下才会调用evthread_make_base_notifiable函数的。- //event.c文件
- int
- evthread_make_base_notifiable(struct event_base *base)
- {
- //默认event回调函数和默认的通知函数
- void (*cb)(evutil_socket_t, short, void *) = evthread_notify_drain_default;
- int (*notify)(struct event_base *) = evthread_notify_base_default;
- /* XXXX grab the lock here? */
- if (!base)
- return -1;
- //th_notify_fd[0]被初始化为-1,如果>=0,就说明已经被设置过了
- if (base->th_notify_fd[0] >= 0)
- return 0;
- #if defined(_EVENT_HAVE_EVENTFD) && defined(_EVENT_HAVE_SYS_EVENTFD_H)
- #ifndef EFD_CLOEXEC
- #define EFD_CLOEXEC 0
- #endif
- //Libevent优先使用eventfd,但eventfd的通信机制和其他的不一样。所以
- //要专门为eventfd创建通知函数和event回调函数
- base->th_notify_fd[0] = eventfd(0, EFD_CLOEXEC);
- if (base->th_notify_fd[0] >= 0) {
- evutil_make_socket_closeonexec(base->th_notify_fd[0]);
- notify = evthread_notify_base_eventfd;
- cb = evthread_notify_drain_eventfd;
- }
- #endif
- #if defined(_EVENT_HAVE_PIPE)
- //<0,说明之前的通知方式没有用上
- if (base->th_notify_fd[0] < 0) {
- //有些多路IO复用函数并不支持文件描述符。如果不支持,那么就不能使用这种
- //通知方式。有关这个的讨论.查看http://blog.csdn.net/luotuo44/article/details/38443569
- if ((base->evsel->features & EV_FEATURE_FDS)) {
- if (pipe(base->th_notify_fd) < 0) {
- event_warn("%s: pipe", __func__);
- } else {
- evutil_make_socket_closeonexec(base->th_notify_fd[0]);
- evutil_make_socket_closeonexec(base->th_notify_fd[1]);
- }
- }
- }
- #endif
- #ifdef WIN32
- #define LOCAL_SOCKETPAIR_AF AF_INET
- #else
- #define LOCAL_SOCKETPAIR_AF AF_UNIX
- #endif
- if (base->th_notify_fd[0] < 0) {
- if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0,
- base->th_notify_fd) == -1) {
- event_sock_warn(-1, "%s: socketpair", __func__);
- return (-1);
- } else {
- evutil_make_socket_closeonexec(base->th_notify_fd[0]);
- evutil_make_socket_closeonexec(base->th_notify_fd[1]);
- }
- }
- //无论哪种通信机制,都要使得读端不能阻塞
- evutil_make_socket_nonblocking(base->th_notify_fd[0]);
- //设置回调函数
- base->th_notify_fn = notify;
- //同样为了让写端不阻塞。虽然,如果同时出现大量需要notify的操作,会塞满通信通道。
- //本次的notify会没有写入到通信通道中(已经变成非阻塞了)。但这无所谓,因为目的是
- //唤醒主线程,通信通道有数据就肯定能唤醒。
- if (base->th_notify_fd[1] > 0)
- evutil_make_socket_nonblocking(base->th_notify_fd[1]);
- //该函数的作用等同于event_new。实际上event_new内部也是调用event_assign函数完成工作的
- //函数cb作为这个event的回调函数
- event_assign(&base->th_notify, base, base->th_notify_fd[0],
- EV_READ|EV_PERSIST, cb, base);
- //标明是内部使用的
- base->th_notify.ev_flags |= EVLIST_INTERNAL;
- event_priority_set(&base->th_notify, 0); //最高优先级
- return event_add(&base->th_notify, NULL);//加入到event_base中。
- }
上面代码展示了,Libevent会从eventfd、pipe和socketpair中选择一种通信方式。由于有三种通信通道可供选择,下文为了方便叙述,就假定它选定的是pipe。
上面代码的工作过程和普通的Libevent例子程序差不多,首先创建一个文件描述符fd,然后用这个fd创建一个event,最后添加到event_base中。
唤醒流程:
现在沿着这个内部的event的工作流程走一遍。
启动notify:
首先往event写入一个字节,开启一切。由于这个event是内部的,用户是接触不到的。所以只能依靠Libevent提供的函数。当然这个函数也不会开放给用户,它只是供Libevent内部使用。
现在来看Libevent内部的需要。在event_add_internal函数中需要通知主线程,在该函数的最后面会调用evthread_notify_base。
- //event.c文件
- static int
- evthread_notify_base(struct event_base *base)
- {
- //确保已经加锁了
- EVENT_BASE_ASSERT_LOCKED(base);
- if (!base->th_notify_fn)
- return -1;
- //写入一个字节,就能使event_base被唤醒。
- //如果处于未决状态,就没必要写多一个字节
- if (base->is_notify_pending)
- return 0;
- //通知处于未决状态,当event_base醒过来就变成已决的了。
- base->is_notify_pending = 1;
- return base->th_notify_fn(base);
- }
在evthread_notify_base中,会调用th_notify_fn函数指针。这个指针是在前面的evthread_make_base_notifiable函数中被赋值的。这里以evthread_notify_base_default作为例子。这个evthread_notify_base_default完成实际的通知操作。
激活内部event:
- //event.c文件。
- static int
- evthread_notify_base_default(struct event_base *base)
- {
- char buf[1];
- int r;
- buf[0] = (char) 0;
- //通知一下,用来唤醒。写一个字节足矣
- #ifdef WIN32
- r = send(base->th_notify_fd[1], buf, 1, 0);
- #else
- r = write(base->th_notify_fd[1], buf, 1);
- #endif
- //即使errno 等于 EAGAIN也无所谓,因为这是由于通信通道已经塞满了
- //这已经能唤醒主线程了。没必要一定要再写入一个字节
- return (r < 0 && errno != EAGAIN) ? -1 : 0;
- }
从上面两个函数看到,其实通知也是蛮简单的。只是往管道里面写入一个字节。当然这已经能使得event_base检测到管道可读,从而实现唤醒event_base。
往管道写入一个字节,event_base就会被唤醒,然后调用这个管道对应event的回调函数。当然,在event_base醒来的时候,还能看到其他东西。这也是Libevent提供唤醒功能的原因。
现在看一下这个唤醒event的回调函数,也是看默认的那个。
- //event.c
- static void
- evthread_notify_drain_default(evutil_socket_t fd, short what, void *arg)
- {
- unsigned char buf[1024];
- struct event_base *base = arg;
- //读完fd的所有数据,免得再次被唤醒
- #ifdef WIN32
- while (recv(fd, (char*)buf, sizeof(buf), 0) > 0)
- ;
- #else
- while (read(fd, (char*)buf, sizeof(buf)) > 0)
- ;
- #endif
- EVBASE_ACQUIRE_LOCK(base, th_base_lock);
- //修改之,使得其不再是未决的了。当然这也能让其他线程可以再次唤醒值。参看evthread_notify_base函数
- base->is_notify_pending = 0;
- EVBASE_RELEASE_LOCK(base, th_base_lock);
- }
这个函数也比较简单,也就是读取完管道里的所有数据,免得被多路IO复用函数检测到管道可读,而再次被唤醒。
上面的流程就完成了Libevent的通知唤醒主线程的功能,思路还是蛮清晰的。实现起来也是很简单。
注意事项:
有一点要注意:要让Libevent支持这种可通知机制,就必须让Libevent使用多线程,即在代码的一开始调用evthread_use_pthreads()或者evthread_use_windows_threads()。虽然用户可以手动调用函数evthread_make_base_notifiable。但实际上是不能实现通知功能的。分析如下:
Libevent代码中是通过调用函数evthread_notify_base来通知的。但这个函数都是在一个if语句中调用的。判断的条件为是否需要通知。If成立的条件中肯定会&&上一个EVBASE_NEED_NOTIFY(base)。比如在event_add_internal函数中的为:
- if (res != -1 && notify && EVBASE_NEED_NOTIFY(base))
- evthread_notify_base(base);
notify是根据函数中的判断而来,而EVBASE_NEED_NOTIFY这个宏定义的作用是判断当前的线程是否不等于主线程(即为event_base执行event_base_dispatch函数的线程)。它是一个条件宏。其中一个实现为:
- #define EVBASE_NEED_NOTIFY(base) \
- (_evthread_id_fn != NULL && \
- (base)->running_loop && \
- (base)->th_owner_id != _evthread_id_fn())
- #define EVTHREAD_GET_ID() \
- (_evthread_id_fn ? _evthread_id_fn() : 1)
event_base结构体中th_owner_id变量指明当前为event_base执行event_base_dispatch函数的是哪个线程。在event_base_loop函数中用宏EVTHREAD_GET_ID()赋值。
如果一开始没有调用evthread_use_pthreads或者evthread_use_windows_threads,那么全局变量evthread_id_fn就为NULL。也就不能获取线程的ID了。EVBASE_NEED_NOTIFY宏也只会返回0,使得不能调用evthread_notify_base函数。关于线程这部分的分析,可以参考《多线程、锁、条件变量(一)》和《多线程、锁、条件变量(二)》。
下面的用一个例子验证。
- #include<event.h>
- #include<stdio.h>
- #include<unistd.h>
- #include<thread.h>
- #include<pthread.h> //Linux thread
- struct event_base *base = NULL;
- void pipe_cb(int fd, short events, void *arg)
- {
- printf("in the cmd_cb\n");
- }
- void timeout_cb(int fd, short events, void *arg)
- {
- printf("in the timeout_cb\n");
- }
- void* thread_fn(void *arg)
- {
- char ch;
- scanf("%c", &ch); //just for wait
- struct event *ev = event_new(base, -1, EV_TIMEOUT | EV_PERSIST,
- timeout_cb, NULL);
- struct timeval tv = {2, 0};
- event_add(ev, &tv);
- }
- int main(int argc, char ** argv)
- {
- if( argc >= 2 && argv[1][0] == 'y')
- evthread_use_pthreads();
- base = event_base_new();
- evthread_make_base_notifiable(base);
- int pipe_fd[2];
- pipe(pipe_fd);
- struct event *ev = event_new(base, pipe_fd[0],
- EV_READ | EV_PERSIST, pipe_cb, NULL);
- event_add(ev, NULL);
- pthread_t thread;
- pthread_create(&thread, NULL, thread_fn, NULL);
- event_base_dispatch(base);
- return 0;
- }
如果次线程的event被add到event_base中,那么每2秒timeout_cb函数就会被调用一次。如果没有被add的话,就永远等待下去,没有任何输出。