c++ 11如何实现简易定时器

  介绍

这篇文章主要讲解了c++ 11如何实现简易定时器,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

定时器定时器是多线程编程中经常设计到的工具类

定时器的原理其实很简单:

    <李>创建一个新线程李 <>李在那个线程里等待李 <李>等待指定时长后做任务李

这里用c++ 11实现了一个简单易用的定时器,包含两种模式:

    <李>周期性定时任务执行 <李>单次延时任务执行

计时器。hpp

的ifndef _TIMER_H_
  #定义_TIMER_H_
  
  # include & lt; functional>
  # include & lt; chrono>
  # include & lt; thread>
  # include & lt; atomic>
  # include & lt; memory>
  # include & lt; mutex>
  # include & lt; condition_variable>
  
  类计时器
  {
  公众:
  计时器():_expired(真实),_try_to_expire(假)
  {}
  
  计时器(const Timer&计时器)
  {
  _expired=timer._expired.load ();
  _try_to_expire=timer._try_to_expire.load ();
  }
  
  ~计时器()
  {
  停止();
  }
  
  空白开始(int区间std:: function<无效()比;任务)
  {//启动,不重新开始
  如果(_expired==false)
  返回;//异步定时器启动,启动线程和线程等
  _expired=false;
  std::线程((间隔,这任务)(){
  而(! _try_to_expire)
  {//睡眠每间隔和做任务一次又一次,直到时间
  std:: this_thread:: sleep_for (std::空间:毫秒(间隔));
  任务();
  }
  
  {//定时器被停止,更新条件变量过期和主线程
  std:: lock_guard储物柜(_mutex);
  _expired=true;
  _expired_cond.notify_one ();
  }
  }).detach ();
  }
  
  空白startOnce (int延迟,std:: function<无效()比;任务)
  {
  std::线程((延迟、任务)(){
  std:: this_thread:: sleep_for (std::空间:毫秒(延迟));
  任务();
  }).detach ();
  }
  
  无效停止()
  {//又不停止
  如果(_expired)
  返回;
  
  如果(_try_to_expire)
  返回;//等待计时器
  _try_to_expire=true;//改变这个bool值让计时器while循环停止
  {
  std:: unique_lock储物柜(_mutex);
  _expired_cond。等待(储物柜,[这]{返回_expired==true;});//重置计时器
  如果(_expired==true)
  _try_to_expire=false;
  }
  }
  
  私人:
  std:: atomic_expired;//定时器停止状态
  std:: atomic_try_to_expire;//定时器是在停止的过程
  std::互斥_mutex;
  std:: condition_variable _expired_cond;
  };
  
  # endif//! _TIMER_H_ 

主要。cpp

 # include & lt; iostream>
  # include“timer.hpp"
  
  空白func1 ()
  {
  std:: cout & lt; & lt;“触发func1"& lt; & lt;std:: endl;
  }
  
  空白func2 (int x)
  {
  std:: cout & lt; & lt;“触发func2 x:“;& lt; & lt;x & lt; & lt;std:: endl;
  }
  
  int主要(int命令行参数个数,char * argv [])
  {
  计时器计时;//执行任务每个定时器间隔
  std:: cout & lt; & lt;“- - - - - -启动时间计时器——“;& lt; & lt;std:: endl;
  计时器。开始(1000年,std::绑定(func2 3));
  std:: this_thread:: sleep_for (std::空间:毫秒(5000));
  timer.stop ();
  std:: cout & lt; & lt;“- - - - - -停止时间计时器——“;& lt; & lt;std:: endl;//执行任务>看完上述内容,是不是对c++ 11如何实现简易定时器有进一步的了解,如果还想学习更多内容,欢迎关注行业资讯频道。

c++ 11如何实现简易定时器