<<C++ Timer实现>>

本文介绍了一个基于C++实现的定时任务系统,该系统通过多线程和条件变量实现了任务调度的功能。支持添加定时任务、停止任务及等待任务执行完毕等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Timer {
public:
typedef std::function<void(void*)> TimerTask;

private:
class TimerTaskWrapper {
public:
TimerTaskWrapper(Timer::TimerTask task, unsigned long timePoint, void* param)
: _task(task), _timePoint(timePoint), _param(param) {
}
virtual ~TimerTaskWrapper() {
}
unsigned long getPoint() const { return _timePoint; }
void setPoint(unsigned long point) { _timePoint = point; }
void* getParam() const { return _param; }
void run() const {
_task(_param);
}

private:
unsigned long _timePoint;
Timer::TimerTask _task;
void* _param;
};

public:
Timer()
: _stopFlag(false) {
_looper = std::thread(std::bind(&Timer::run, this));
}
virtual ~Timer() {
}
void start(TimerTask task, long long timePoint, void* param) {
std::lock_guard<std::mutex> guard(_queueMutex);
_queue.emplace_back(task, timePoint, param);
if (1 == _queue.size()) {
std::unique_lock <std::mutex> lock(_cvMutex);
_queueCV.notify_all();
}
}
void stop() {
_stopFlag = true;
}
void join() {
if (_looper.joinable()) _looper.join();
}

private:
TimerTaskWrapper popMinTask() {
std::lock_guard<std::mutex> guard(_queueMutex);
int minIndex = 0;
for (int i = 1; i < _queue.size(); ++i) {
if (_queue.at(minIndex).getPoint() > _queue.at(i).getPoint()) {
minIndex = i;
}
}
auto task = _queue.at(minIndex);
_queue.erase(_queue.begin() + minIndex);
return task;
}

void run() {
while (!_stopFlag) {
{
std::unique_lock <std::mutex> lock(_cvMutex);
while (_queue.empty()) _queueCV.wait(lock);
}
auto task = popMinTask();
{
std::unique_lock <std::mutex> lock(_timeoutMutex);
_timeoutCV.wait_for(lock, std::chrono::milliseconds(task.getPoint()));
}
task.run();
}
}

private:
std::atomic_bool _stopFlag;
std::mutex _queueMutex;
std::mutex _cvMutex;
std::mutex _timeoutMutex;
std::thread _looper;
std::condition_variable _queueCV;
std::condition_variable _timeoutCV;
std::vector<TimerTaskWrapper> _queue;
};

转载于:https://www.cnblogs.com/intelligentfish/p/7161285.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值