文章目录
定时器
#include <iostream>
#include <event2/event.h>
#ifndef _WIN32
#include <signal.h>
#endif
using namespace std;
static timeval t1 = { 1,0 };
void timer1(int sock, short which, void *arg) {
cout << "[timer1]" << flush;
event* ev = (event*)arg;
if (!evtimer_pending(ev,&t1)){
evtimer_del(ev);
evtimer_add(ev, &t1);
}
}
void timer2(int sock, short which, void* arg) {
cout << "[timer2]" << flush;
}
int main(int argc, char** argv) {
#if _WIN32
//windowns 初始化socket库
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
#else
//linux 忽略管道信号,发送数据给已关闭的socket
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
return 1;
#endif
event_base* base = event_base_new();
//定时器处理(非持久事件只进入一次)
event* ev1 = evtimer_new(base, timer1, event_self_cbarg());
if (!ev1)
{
cout << "evtimer_new ev1 failed!" << endl;
return -1;
}
evtimer_add(ev1, &t1);
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_base_dispatch(base);
event_base_free(base);
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return 0;
}
定时器优化
#include <iostream>
#include <event2/event.h>
#include <thread>
#ifndef _WIN32
#include <signal.h>
#endif
using namespace std;
static timeval t1 = { 1,0 };
void timer1(int sock, short which, void *arg) {
cout << "[timer1]" << flush;
event* ev = (event*)arg;
if (!evtimer_pending(ev,&t1)){
evtimer_del(ev);
evtimer_add(ev, &t1);
}
}
void timer2(int sock, short which, void* arg) {
cout << "[timer2]" << flush;
this_thread::sleep_for(3000ms);//睡眠3秒
}
void timer3(int sock, short which, void* arg) {
cout << "[timer3]" << flush;
}
int main(int argc, char** argv) {
#if _WIN32
//windowns 初始化socket库
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
#else
//linux 忽略管道信号,发送数据给已关闭的socket
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
return 1;
#endif
event_base* base = event_base_new();
//定时器处理(非持久事件只进入一次)
event* ev1 = evtimer_new(base, timer1, event_self_cbarg());
if (!ev1)
{
cout << "evtimer_new ev1 failed!" << endl;
return -1;
}
evtimer_add(ev1, &t1);
//定时器处理(持久事件)
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);//插入删除性能O(logN)
//超时优化,性能优化, 默认event用二叉堆存储(二叉树,OlogN)
//优化到双向队列,插入删除O(1)
static timeval tv_in = { 3,0 };
const timeval* t3;
t3 = event_base_init_common_timeout(base, &tv_in);
event* ev3 = event_new(base, -1, EV_PERSIST, timer3, 0);
event_add(ev3, t3); //插入删除性能O(1)
//进入事件主循环
event_base_dispatch(base);
event_base_free(base);
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return 0;
}