一个基于C++11的定时器队列(timerfd,poll实现)
2019-01-24 11:00
225 查看
目录
@
前言
最近小程序要用到定时器,找了一圈也没找到合适的,最后还是绕回来选择了muduo里面的TimerQueue,整理了下它的代码,独立了出来,因为实在懒得从头写一个- -!。
原来的muduo中TimerQueue是专为EventLoop提供定时功能的组件,我在笔记
muduo网络库学习笔记(三)TimerQueue定时器队列中解读过muduo这块代码,现在反过来,EventLoop做为TimerQueue的组件,TimerQueue启动后在后面开一个线程跑EventLoop,EventLoop里面进行阻塞的poll循环,只监听timerFd,和EventFd,从而独立出来一个单独的定时器队列。。
优点
[Async] [thread-safe] [based on poll] [microseconds-level]
异步:后台线程监视文件描述符动态。
线程安全: 多线程安全的 支持异步插入定时器。
基于poll: 非休眠机制实现。
级别: 微妙级别。
test
#include <chrono> #include <iostream> #include "Logger.hpp" #include "TimerQueue.hpp" void test() { LOG_DEBUG << "[test] : test timerQue happended "; std::cout << "[test] : test timerQue happended at " << std::chrono::system_clock::now().time_since_epoch() / std::chrono::microseconds(1) << std::endl; } int main() { //Logger::setLogLevel(Logger::TRACE); TimerQueue* timer_queue = TimerQueue::GetInstance(); timer_queue->Start(); timer_queue->runAfter(1.0, test); timer_queue->runAfter(1.0, test); timer_queue->runAfter(3.0, test); timer_queue->runEvery(5.0, test); getchar(); return 0; }
./timer_queue_test
[test] : test timerQue happended at 15482931
90811373
[test] : test timerQue happended at 15482931
90811392
[test] : test timerQue happended at 15482931
92811787
[test] : test timerQue happended at 15482931
94811927
[test] : test timerQue happended at 15482931
99812081
[test] : test timerQue happended at 15482932
04812645
[test] : test timerQue happended at 15482932
09813508
源代码
TimerQueue: https://github.com/BethlyRoseDaisley/TimerQueue/tree/master/TimerQueue 欢迎收藏。
相关文章推荐
- linux网络编程二十一:利用SIGALRM信号,实现一个简单的基于升序链表的定时器
- 这里实现一个基于数组的线程安全的循环队列
- 用golang实现一个定时器任务队列实例
- 用两个栈来实现一个队列,完成队列的add和poll、peek操作。
- 数据结构 编写一个类,用两个栈实现队列,支持队列的基本操作(add 、poll、peek)
- 用c++11的bind,function,boost::condition_variable实现的一个线程安全的任务队列
- 如何用golang实现一个定时器任务队列
- 生产消费者4 - 实现一个基于优先级的传输队列【消费顺序是由优先级决定的而不是抵达时间】
- 教你如何使用Java手写一个基于数组实现的队列
- 基于c++11设计一个定时器timer
- 一个基于NIO的下载队列实现
- 基于HashedWheelTimer的一个定时器实现
- 实现一个基于双向链表的双端队列
- 实现一个基于LinkedList的队列数据结构,去除ArrayList集合中重复的元素,
- 实现一个简单的基于asio的定时器
- 二、 编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek)
- 用java实现一个基于堆排序的优先队列
- 基于ACE的定时器队列实现
- C++11:基于std::queue和std::mutex构建一个线程安全的队列
- 基于C++11的阻塞队列简单实现