c++11实现异步定时器
c++11提供了丰富的时间和线程操作函数,比如 std::this_thread::sleep, std::chrono::seconds等。可以利用这些来很方便的实现一个定时器。
定时器要求在固定的时间异步执行一个操作,比如boost库中的boost::asio::deadline_timer,以及MFC中的定时器。这里,利用c++11的thread, mutex, condition_variable 来实现一个定时器:
定时器要求异步执行任务 ----> 开辟独立的线程
定时器要求能够启动和取消 ----> 提供安全的取消操作,使用互斥量和信号量
定时器要求每个定时时刻到达的时候执行的任务要尽可能节省时间
实现
#ifndef TIMER_H_
#define TIMER_H_
#include<functional>
#include<chrono>
#include<thread>
#include<atomic>
#include<memory>
#include<mutex>
#include<condition_variable>
class Timer{
public:
Timer() :expired_(true), try_to_expire_(false){
} Timer(const Timer& t){
expired_ = t.expired_.load();
try_to_expire_ = t.try_to_expire_.load();
}
~Timer(){
Expire();
// std::cout << "timer destructed!" << std::endl;
} void StartTimer(int interval, std::function<void()> task){
if (expired_ == false){
// std::cout << "timer is currently running, please expire it first..." << std::endl;
return;
}
expired_ = false;
std::thread([this, interval, task](){
while (!try_to_expire_){
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
task();
}
// std::cout << "stop task..." << std::endl;
{
std::lock_guard<std::mutex> locker(mutex_);
expired_ = true;
expired_cond_.notify_one();
}
}).detach();
} void Expire(){
if (expired_){
return;
} if (try_to_expire_){
// std::cout << "timer is trying to expire, please wait..." << std::endl;
return;
}
try_to_expire_ = true;
{
std::unique_lock<std::mutex> locker(mutex_);
expired_cond_.wait(locker, [this]{return expired_ == true; });
if (expired_ == true){
// std::cout << "timer expired!" << std::endl;
try_to_expire_ = false;
}
}
} template<typename callable, class... arguments>
void SyncWait(int after, callable&& f, arguments&&... args){ std::function<typename std::result_of<callable(arguments...)>::type()> task
(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}
template<typename callable, class... arguments>
void AsyncWait(int after, callable&& f, arguments&&... args){
std::function<typename std::result_of<callable(arguments...)>::type()> task
(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...)); std::thread([after, task](){
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}).detach();
} private:
std::atomic<bool> expired_;
std::atomic<bool> try_to_expire_;
std::mutex mutex_;
std::condition_variable expired_cond_;
};
#endif ////////////////////test.cpp
#include<iostream>
#include<string>
#include<memory>
#include"Timer.hpp"
using namespace std;
void EchoFunc(std::string&& s){
std::cout << "test : " << s << endl;
} int main(){
Timer t;
//周期性执行定时任务
t.StartTimer(1000, std::bind(EchoFunc,"hello world!"));
std::this_thread::sleep_for(std::chrono::seconds(4));
std::cout << "try to expire timer!" << std::endl;
t.Expire(); //周期性执行定时任务
t.StartTimer(1000, std::bind(EchoFunc, "hello c++11!"));
std::this_thread::sleep_for(std::chrono::seconds(4));
std::cout << "try to expire timer!" << std::endl;
t.Expire(); std::this_thread::sleep_for(std::chrono::seconds(2)); //只执行一次定时任务
//同步
t.SyncWait(1000, EchoFunc, "hello world!");
//异步
t.AsyncWait(1000, EchoFunc, "hello c++11!"); std::this_thread::sleep_for(std::chrono::seconds(2)); return 0;
}
c++11实现异步定时器的更多相关文章
- boost库学习随记六:使用同步定时器、异步定时器、bind、成员函数回调处理、多线程的同步处理示例等
一.使用同步定时器 这个示例程序通过展示如何在一个定时器执行一个阻塞等待. //makefile #-------------------------------------------------- ...
- 2018.2.11 JS的定时器制作
定时器 1.定时器定义 var time = window.setInterval("执行名词",间隔时间) 关闭定时器 clearInterval(定时器名称) 倒计时定时器 s ...
- 使用boost的deadline_timer实现一个异步定时器
概述 最近在工作上需要用到定时器,然后看到boost里面的deadline_timer可以实现一个定时器,所以就直接将其封装成了ATimer类,方便使用,ATimer有以下优点: 可以支持纳秒.毫秒. ...
- C++11 使用异步编程std::async和std::future
先说明一点:std::asyanc是std::future的高级封装, 一般我们不会直接使用std::futrue,而是使用对std::future的高级封装std::async. 下面分别说一下. ...
- 2015.3.11 VS异步控件及进度条结合应用
1.在Form中添加 指针控件:BackgroundWorker-bgwork:进度条控件progressBar1 以及开始.取消按钮 2.开始按钮启动异步线程 private void button ...
- 11 Windows编程——定时器
周期性的发送WWL_TIMER消息的一个东西,这个周期可以由程序员自己设定.设定周期的数是SetTimer,停止定时器消息发送的函数是:Killximer: 定时器消息的特点: 1.不准确(也就是说, ...
- 2020.11.2 异步IO 协程
异步IO 同步IO在一个线程中,CPU执行代码的速度极快,然而,一旦遇到IO操作,如读写文件.发送网络数据时,就需要等待IO操作完成,才能继续进行下一步操作. 在IO操作的过程中,当前线程被挂起,而其 ...
- 第11章 Windows线程池(1)_传统的Windows线程池
第11章 Windows线程池 11.1 传统的Windows线程池及API (1)线程池中的几种底层线程 ①可变数量的长任务线程:WT_EXECUTELONGFUNCTION ②Timer线程:调用 ...
- CoreAnimation6-基于定时器的动画和性能调优
基于定时器的动画 定时帧 动画看起来是用来显示一段连续的运动过程,但实际上当在固定位置上展示像素的时候并不能做到这一点.一般来说这种显示都无法做到连续的移动,能做的仅仅是足够快地展示一系列静态图片,只 ...
随机推荐
- 【火狐FireFox】同步失败后,书签被覆盖,如何恢复书签
问题场景: 使用公司的电脑,下载安装火狐,登录个人帐号后,火狐会自动开始同步书签.但有时候会同步失败,比如登录之前选的是[本地服务],而最新的书签都是在[全球服务]理,那么很有可能同步到的是N久之前的 ...
- java日期工具类DateUtil-续二
该版本是一次较大的升级,农历相比公历复杂太多(真佩服古人的智慧),虽然有规律,但涉及到的取舍.近似的感念太多,况且本身的概念就已经很多了,我在网上也是查阅了很多的资料,虽然找到一些计算的方法,但都有些 ...
- Smack 广播
格式 Message message = new Message("all@broadcast.192.168.1.253"); 使用openfire的广播功能首先需要在插件的页面 ...
- java中的方法——重载yu重写(转)
重载(Overloading) (1) 方法重载是让类以统一的方式处理不同类型数据的一种手段.多个同名函数同时存在,具有不同的参数个数/类型. 重载Overloading是一个类中多态性的一种表现. ...
- 关于ajax get方式请求 url地址参数怎么变成空了的问题
如URL地址:http://i.cnblogs.com/EditPosts.aspx?opt=1&value=#sgsgs; 今天在做项目中发现value明明是有值,怎么出在的后台往往取不到 ...
- JS实现复制到剪贴板(兼容FF/Chrome/Safari所有浏览器)
现在浏览器种类也越来越多,诸如 IE.Firefox.Chrome.Safari等等,因此现在要实现一个js复制内容到剪贴板的小功能就不是一件那么容易的事了. 在FLASH 9 时代,有一个通杀所有浏 ...
- selenium测试(Java)--浏览器控制(四)
1. 控制浏览器窗口大小 1 package com.test.window; 2 3 import org.openqa.selenium.Dimension; 4 import org.openq ...
- 最小顶点覆盖(Minimum Vertex Cover)与最大独立集(Maximum Independent Set)
问题描述:就是在图中找最小的点集,使得覆盖所有边. 和独立集等价:独立集问题:在图中找最大的点集,使得点集内的所有点互不相连. 引理:顶点覆盖集和独立集互补. 上面这个引理使得这两个问题可以相互规约, ...
- Android Studio编译错误:Unexpected lock protocol found in lock file. Expected 3, found 0.
如果不小心手动修改了.gradle文件夹中的内容,那么再打开之前编译成功的工程时,会出现类似下面的错误: Gradle app neame project refresh failed: Unexpe ...
- am335x reboot 命令分析
本文记录am335x运行reboot命令时,内核中运行过程. Tony Liu, 2016-6-8, Shenzhen 参考链接: http://blog.csdn.net/wavemcu/artic ...