c++实现自定义的定时器源代码

博客提及代码来源为“跑步客”,未包含更多信息技术相关关键信息。

 

#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <atomic>

class Timer {
public:
    enum class Mode {
        SINGLE_SHOT,
        PERIODIC
    };

    Timer() : m_expired(true), m_try_to_expire(false) {}

    ~Timer() {
        stop();
    }

    void start(int interval, std::function<void()> task, Mode mode = Mode::PERIODIC) {
        if (!m_expired.load()) return;
        
        m_expired.store(false);
        m_thread = std::thread([this, interval, task, mode]() {
            std::unique_lock<std::mutex> lock(m_mutex);
            while (!m_try_to_expire.load()) {
                if (m_cv.wait_for(lock, std::chrono::milliseconds(interval), 
                                 [this] { return m_try_to_expire.load(); })) {
                    break;
                }
                task();
                if (mode == Mode::SINGLE_SHOT) {
                    break;
                }
            }
            m_expired.store(true);
            m_try_to_expire.store(false);
        });
    }

    void stop() {
        if (m_expired.load() || m_try_to_expire.load()) {
            return;
        }
        m_try_to_expire.store(true);
        m_cv.notify_one();
        if (m_thread.joinable()) {
            m_thread.join();
        }
    }

private:
    std::atomic<bool> m_expired;
    std::atomic<bool> m_try_to_expire;
    std::mutex m_mutex;
    std::condition_variable m_cv;
    std::thread m_thread;
};
 

int main() {
    Timer timer;
    
    // 单次定时器
    timer.start(1000, [] {
        std::cout << "Single shot timer triggered!" << std::endl;
    }, Timer::Mode::SINGLE_SHOT);

    std::this_thread::sleep_for(std::chrono::milliseconds(2000));
    
    // 周期定时器
    timer.start(500, [] {
        std::cout << "Periodic timer triggered!" << std::endl;
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(3000));
    timer.stop();
    
    return 0;
}
 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

paobuke

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值