C++11实现简易定时器的示例代码实现简易定时器的示例代码
定时器timer是多线程编程中经常设计到的工具类
定时器的原理其实很简单:
创建一个新线程
在那个线程里等待
等待指定时长后做任务
这里用C++11实现了一个简单易用的定时器,包含两种模式:
周期性定时任务执行
单次延时任务执行
timer.hpp
#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& timer)
{
_expired = timer._expired.load();
_try_to_expire = timer._try_to_expire.load();
}
~Timer()
{
stop();
}
void start(int interval, std::function<void()> task)
{
// is started, do not start again
if (_expired == false)
return;
// start async timer, launch thread and wait in that thread
_expired = false;
std::thread([this, interval, task]() {
while (!_try_to_expire)
{
// sleep every interval and do the task again and again until times up
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
task();
}
{
// timer be stopped, update the condition variable expired and wake main thread
std::lock_guard<std::mutex> locker(_mutex);
_expired = true;
_expired_cond.notify_one();
}
}).detach();
}
评论5