概述
test.cpp
#include <iostream>
#include <thread>
#include <event2/event.h>
#include <event2/event.h>
#include <event2/thread.h>
#include<event2/listener.h>
#ifndef _WIN32
#include <signal.h>
#else
#endif
using namespace std;
static timeval t1 = { 1,0 };
void timer1(int sock, short which, void* arg)
{
event* ev = (event *)arg;
cout << "[ timer1 ]" << endl;
if (!evtimer_pending(ev, &t1))
{
evtimer_del(ev);
evtimer_add(ev, &t1);
}
}
void timer2(int sock, short which, void* arg)
{
cout << "[ timer2 ]" << endl;
this_thread::sleep_for(3000ms);
}
void timer3(int sock, short which, void* arg)
{
cout << "[ timer3 ]" << endl;
}
int main(int argc, char** argv)
{
#ifdef _WIN32
//初始化socket库
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
#else
//忽略管道信号,发送数据给已关闭的socket
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
return 1;
#endif
event_base* base = event_base_new();
//定时器
cout << "timer ->" << endl;
//定时器,非持久事件,只进入一次
event* evl = evtimer_new(base, timer1, event_self_cbarg());
if (!evl)
{
cout << "evtimer_new timer1 failed! " << endl;
return -1;
}
evtimer_add(evl, &t1); //插入性能O(log n)
static timeval t2;
t2.tv_sec = 1;
t2.tv_usec = 200000;//微秒
event* ev2 = event_new(base, -1, EV_PERSIST, timer2, 0);
event_add(ev2, &t2);
event* ev3 = event_new(base, -1, EV_PERSIST, timer3, 0);
//对超时性能优化,默认event用完全二叉树存储,插入输出都是O(log n)
//优化到双向队列 插入和删除O(1)
static timeval tv_in = { 3,0 };
const timeval* t3;
t3 = event_base_init_common_timeout(base, &tv_in);
event_add(ev3, t3); //插入性能O(1)
//进入事件主循环
event_base_dispatch(base);
event_base_free(base);
return 0;
}
linux下makefile
test:test.cpp
g++ $^ -o $@ -levent
./$@
clean:
rm -rf test
rm -rf *.o
最后
以上就是曾经日记本为你收集整理的08.libevent定时器的优化的全部内容,希望文章能够帮你解决08.libevent定时器的优化所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复