libevent 初试

一直就想用一下libevent库,直到今天才去码代码。用法在他的头文件里面写的很清楚,原理的话也不是很难,感谢作者做的工作!

今天做了几个探索:

  • 实现自定义事件类型的设置与触发
  • 尝试 setInterval 类似的功能
  • event loop 无限等待loop,直到手动关闭程序
#include <iostream>
#include <event2/event.h>
#include <event2/util.h>
#include <sys/time.h>
#include <time.h>
#include <signal.h>
using namespace std;

#define MY_EVENT_TRAN 10000 //定义自己的事件

struct event_base *base;

void test_cb(int sock,short event,void*args){
 cout<<"sock"<<sock<<"  "<<"event:"<<event<<endl;
 cout<<*((string *)args)<<endl;
}

void app_exit(int sock,short event,void*args){
  cout<<"signal exit"<<endl;
  event_base_loopexit(base,0);
}

void self_event_cb(int sock,short event,void *args){
 cout<<"sock"<<sock<<"  "<<"event:"<<event<<endl;
 cout<<((int*)args)[0]<<endl;
}

int main()
{

    base=event_base_new();

    string msg="hello world";
    struct timeval timeout;
    timeout.tv_sec=10;
    timeout.tv_usec=10;

    int *m=new int[1];
    m[0]=10;
	
	//int m=10; !important 将这样定义的作为参数传给回调函数会报内存错误,传给回调的参数的内存必须是从heap上申请的。
	
    struct event *my_event=event_new(base,-1,EV_PERSIST,test_cb,&msg);
    struct event *my_event2=event_new(base,-1,EV_PERSIST,self_event_cb,m);
    struct event *sig_event=event_new(base,SIGINT,EV_SIGNAL|EV_PERSIST,app_exit,0);
	
    evsignal_initialized(sig_event);
	
    event_add(my_event,NULL);
    event_add(my_event2,&timeout);//每隔10010毫秒触发一次这个事件,event_del()可以删除该事件
    event_add(sig_event,NULL);
    event_active(my_event,MY_EVENT_TRAN,0);//activate self define event 

    event_base_dispatch(base);
    delete[]m;
    event_free(my_event);
    event_free(my_event2);
    event_free(sig_event);
    event_base_free(base);
    return 0;
}

环境: libevent-2.0.22-stable ubuntu 16.4 gnome codeblocks

posted @ 2016-10-16 20:55  yyrdl  阅读(200)  评论(0编辑  收藏  举报