全站数据
8 4 2 0 5 8 1

c++定时器

小药师 | 简单学习,快乐成才!         
问题更新日期:2024-10-20 02:06:49

问题描述

c++定时器急求答案,帮忙回答下
精选答案
最佳答案

#ifndef CTimer_hpp

#define CTimer_hpp

#include <stdio.h>

#include <functional>

#include <chrono>

#include <thread>

#include <atomic>

#include <mutex>

#include <string>

#include <condition_variable>

class CTimer

{

public:

CTimer(const std::string sTimerName =

"

"); //构造定时器,附带名称

~CTimer();

bool Start(unsigned int msTime, std::function<void()> task, bool bLoop = false, bool async = true);

void Cancel();

template<typename callable, typename... arguments>

bool SyncOnce(int msTime, callable&& fun, arguments&&... args) {

std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(fun), std::forward<arguments>(args)...)); //绑定任务函数或lambda成function

return Start(msTime, task, false, false);

}

template<typename callable, typename... arguments>

bool AsyncOnce(int msTime, callable&& fun, arguments&&... args) {

std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(fun), std::forward<arguments>(args)...));

return Start(msTime, task, false);

}

template<typename callable, typename... arguments>

bool AsyncOnce(callable&& fun, arguments&&... args) {

std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(fun), std::forward<arguments>(args)...));

return Start(1, task, false);

}

template<typename callable, typename... arguments>

bool AsyncLoop(int msTime, callable&& fun, arguments&&... args) {

std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(fun), std::forward<arguments>(args)...));

return Start(msTime, task, true);

}

private:

void DeleteThread();//删除任务线程

public:

int m_nCount = 0; //循环次数

private:

std::string m_sName; //定时器名称

std::atomic_bool m_bExpired; //装载的任务是否已经过期

std::atomic_bool m_bTryExpired;//装备让已装载的任务过期(标记)

std::atomic_bool m_bLoop;//是否循环

std::thread *m_Thread = nullptr;

std::mutex m_ThreadLock;

std::condition_variable_any m_ThreadCon;

};