首页 > 代码库 > libevent和libev的区别对比(二)

libevent和libev的区别对比(二)

之前有一篇文章描述过一些对比:

http://www.cnblogs.com/charlesblc/p/6078029.html

 

这里在代码和应用方面再说一下。

看一下两边的Helloworld基本就了解个大概。

 

libevent的hello world

#include <sys/signal.h>
#include <event.h>

void signal_cb(int fd, short event, void *arg) {
        event_base *base = (event_base*) arg;
        timeval delay = {2, 0};
        printf("Caught an interrupt signal, exit in 2 sec...\n");
        event_base_loopexit(base, &delay);
}

void timeout_cb(int fd, short event, void *arg) {
        printf("timeout\n");
}

int main() {
        event_base *base = event_init();
        event *signal_event = evsignal_new(base, SIGINT, signal_cb, base);
        event_add(signal_event, NULL);

        timeval tv = {1, 0};
        event * timeout_event = evtimer_new(base, timeout_cb, NULL);
        event_add(timeout_event, &tv);

        event_base_dispatch(base);

        event_free(timeout_event);
        event_free(signal_event);
        event_base_free(base);

}

 

上面Libevent最基本的事件驱动器是 event_base *base = event_init(); 下面libev最基本的事件驱动器是 struct ev_loop *main_loop = ev_default_loop(0);

上面Libevent的事件,在初始化的时候,会把驱动器加进去,event *signal_event = evsignal_new(base, SIGINT, signal_cb, base); 然后直接event_add就行了,这时候不用加驱动器;

下面libev的事情,在初始化的时候,不涉及驱动器,先关联事件和回调函数:ev_init(&io_w,io_action); 再绑定事件源:ev_io_set(&io_w,STDIN_FILENO,EV_READ);  最后再向驱动器注册:ev_io_start(main_loop,&io_w);

上面Libevent开始事件循环用 event_base_dispatch(base); 下面libev开始事件循环用 ev_run(main_loop,0);

 

libev的hello world

#include<ev.h>
#include <stdio.h>
#include <signal.h>
#include <sys/unistd.h>

ev_io io_w;
ev_timer timer_w;
ev_signal signal_w;

void io_action(struct ev_loop *main_loop,ev_io *io_w,int e)
{
        int rst;
        char buf[1024] = {‘\0‘};
        puts("in io cb\n");
        read(STDIN_FILENO,buf,sizeof(buf));
        buf[1023] = ‘\0‘;
        printf("Read in a string %s \n",buf);
        ev_io_stop(main_loop,io_w);

}

void timer_action(struct ev_loop *main_loop,ev_timer *timer_w,int e)
{
        puts("in tiemr cb \n");
        ev_timer_stop(main_loop,timer_w);

}

void signal_action(struct ev_loop *main_loop,ev_signal signal_w,int e)
{
        puts("in signal cb \n");
        ev_signal_stop(main_loop,signal_w);
        ev_break(main_loop,EVBREAK_ALL);
}

int main(int argc ,char *argv[])
{
        struct ev_loop *main_loop = ev_default_loop(0);
        ev_init(&io_w,io_action);
        ev_io_set(&io_w,STDIN_FILENO,EV_READ);  
        ev_init(&timer_w,timer_action);
        ev_timer_set(&timer_w,2,0);       
        ev_init(&signal_w,signal_action);
        ev_signal_set(&signal_w,SIGINT); 

        ev_io_start(main_loop,&io_w);
        ev_timer_start(main_loop,&timer_w);
        ev_signal_start(main_loop,&signal_w);

        ev_run(main_loop,0);

return 0;
}

 

libevent和libev的区别对比(二)