Chinaunix首页 | 论坛 | 博客
  • 博客访问: 92708
  • 博文数量: 31
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 380
  • 用 户 组: 普通用户
  • 注册时间: 2014-02-24 22:04
文章分类

全部博文(31)

文章存档

2014年(31)

我的朋友

分类: C/C++

2014-05-29 14:52:39




点击(此处)折叠或打开

  1. int lasttime;

  2. static void
  3. timeout_cb(int fd, short event, void *arg)    //事件回调函数
  4. {
  5.     struct timeval tv;
  6.     struct event *timeout = arg;   //获取事件
  7.     int newtime = time(NULL);      //得到当前时间

  8.     printf("%s: called at %d: %d\n", __func__, newtime,
  9.      newtime - lasttime);   //表示经过了多少时间,回调函数被执行
  10.     lasttime = newtime;   //重新设定lasttime为当前时间

  11.     evutil_timerclear(&tv);   
  12.     tv.tv_sec = 2;
  13.     event_add(timeout, &tv);   //重新绑定超时事件
  14. }

点击(此处)折叠或打开

  1. int
  2. main (int argc, char **argv)
  3. {
  4.     struct event timeout;   //定义一个事件eventout,这里主要是举例liebevent的超时事件的执行步骤,所以事件名称是timeout
  5.     struct timeval tv;    //定义时间
  6.  
  7.     /* Initalize the event library */
  8.     event_init();    //初始化event_base,这里初始化系统中的一个名为current_base的全局event_base对象

  9.     /* Initalize one event */
  10.     evtimer_set(&timeout, timeout_cb, &timeout);    //设定timeout这个事件的回调函数timeout_cb与参数&timeout

  11.     evutil_timerclear(&tv);    //把tv中的时间清零
  12.     tv.tv_sec = 2;   //设定时间=2s
  13.     event_add(&timeout, &tv);    //绑定这个事件到默认的event_base中,也就是current_base

  14.     lasttime = time(NULL);    //获取当前时间
  15.     
  16.     event_dispatch();    //执行事件分发

  17.     return (0);
  18. }

下面从这个timeout事件的这个例子中来分析
(1) 首先定义一个事件,名字为timeout
(2) 调用event_init()初始化全局对象current_base
(3) 调用evtimer_set()设置事件的回调函数与参数
(4) 调用event_add()绑定这个事件到currren_base
(5) 执行事件分发函数event_dispatch()


在后续的文章中,将陆续对上面的步骤所设计到的代码进行详细的分析




阅读(672) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~