libevent(2): 超时机制分析

先上一段libevent提供的代码:
int lasttime;

static void
timeout_cb(int fd, short event, void *arg)
{
	struct timeval tv;
	struct event *timeout = arg;
	int newtime = time(NULL);

	printf("%s: called at %d: %d\n", __func__, newtime,
	    newtime - lasttime);
	lasttime = newtime;

	evutil_timerclear(&tv);
	tv.tv_sec = 2;
	event_add(timeout, &tv);
}

int
main (int argc, char **argv)
{
	struct event evTimeout;
	struct timeval tvElapse;
 
	/* Initalize the event library */
	event_init();

	/* Initalize one event */
	evtimer_set(&evTimeout, timeout_cb, &evTimeout);

	evutil_timerclear(&tvElapse);
	tvElapse.tv_sec = 2;
	event_add(&evTimeout, &tvElapse);

	lasttime = time(NULL);
	
	event_dispatch();

	return (0);
}

跟踪发现添加超时事件流程为:

evtimer_set --> event_add --> event_queue_insert --> min_heap_push

(构造超时结构体)
(将该结构体加入到主事件中)

最终我们发现是加入到最小堆中。


那么何时,如何调用该事件呢?

event_base_loop --> event_process_active --> (*ev->ev_callback)((int)ev->ev_fd, ev->ev_res, ev->ev_arg);

这样完成了。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值