惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
博客园 - Franky
博客园 - 三生石上(FineUI控件)
爱范儿
爱范儿
博客园 - 司徒正美
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
美团技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
B
Blog RSS Feed
阮一峰的网络日志
阮一峰的网络日志
宝玉的分享
宝玉的分享
V
Visual Studio Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
博客园_首页
S
SegmentFault 最新的问题
A
About on SuperTechFans
Blog — PlanetScale
Blog — PlanetScale
GbyAI
GbyAI
H
Help Net Security
MongoDB | Blog
MongoDB | Blog

博客园 - osbreak

ros2::tf2 QML::qml与c++数据交互 k8s:: Service 管理 deployment postgresql 索引 postgresql 基本类型 postgresql 基础运维 PLSQL 触发器 PLSQL 程序包 PLSQL 执行块 PLSQL 基础数据类型 PLSQL oracle安装部署 mysql事务与隔离 mysql慢查询分析 mysql建增删改查 mysql常用总结 (9)libevent 常用设置 (8)libevent 构建libevent http服务,支持文件下载 (7)libevent filter(过滤器) (5)libevent evbuffer
(6)libevent定时器
osbreak · 2023-11-09 · via 博客园 - osbreak

libevent事件

一、libevent非持久定时器

#include <iostream>
#include <event2/event.h>
#include <signal.h>
using namespace std;

static timeval t1 = { 1, 0 };	// 1秒0毫秒

void timer(int sockfd, short what, void* arg) {
	cout << "[ timer 1s ]" << flush;
	event* ev = (event*)arg;
	// 非持久定时器, 再次添加定时任务
	if (!evtimer_pending(ev, &t1)) {
		evtimer_del(ev);
		evtimer_add(ev, &t1);
	}
}

int main(int argc, char* argv[])
{
	event_base* base = event_base_new();
	
	//定时器,非持久事件
	event* timer_ev = evtimer_new(base, timer, event_self_cbarg());
	if (!timer_ev) {
		cout << "evtimer_new failed!" << endl;
		return 1;
	}
	
	evtimer_add(timer_ev, &t1); // 插入性能 O(logn)
	
	//进入事件主循环
	event_base_dispatch(base);
	event_base_free(base);
	return 0;
}

二、libevent持久定时器

#include <iostream>
#include <event2/event.h>
#include <signal.h>
using namespace std;

void timer(int sockfd, short what, void* arg) {
	cout << "[timer2]" << endl;
}

int main(int argc, char* argv[])
{
	event_base* base = event_base_new();

	// 持久事件
	static timeval t2;
	t2.tv_sec = 1;
	t2.tv_usec = 200000;//微秒
	event* persist_timer = event_new(base, -1, EV_PERSIST, timer, 0);
	event_add(persist_timer, &t2);  //插入性能 O(logn)

	// 进入事件主循环
	event_base_dispatch(base);
	event_base_free(base);
	return 0;
}

二、优化libevent超时

#include <iostream>
#include <event2/event.h>
#include <signal.h>
using namespace std;

void timer(int sockfd, short what, void* arg) {
	cout << "[timer2]" << endl;
}

int main(int argc, char* argv[])
{
	event_base* base = event_base_new();
	
	// 持久事件
	event *ev = event_new(base,-1,EV_PERSIST,timer,0);
	//超时优化性能优化,默认event 用二叉堆存储(完全二叉树) 插入删除O(logn)
	//优化到双向队列 插入删除O(1)
	static timeval tv_in = {3,0};
	const timeval *t;
	t = event_base_init_common_timeout(base,&tv_in);
	event_add(ev3,t3); // 性能优化:插入性能 O(1)

	// 进入事件主循环
	event_base_dispatch(base);
	event_base_free(base);
	return 0;
}